Search code examples
javascriptecmascript-5

Javascript `filter` + `reduce` VS `reduce` + `if`


Object.entries(obj).reduce((acc, [key, value]) => {
  if (someCondition(key, value)) {
    acc[key] = value;
  }
  return acc;
}, {});


Object.entries(obj)
  .filter(([key, value]) => someCondition(key, value))
  .reduce((acc, [key, value]) => {
    acc[key] = value;
    return acc;
  }, {});

The above two blocks do the same thing: create a copy of obj with some properties removed based on someCondition.

Which way is preferred and why?


Solution

  • It always depends.

    With the first case - reduce with condition inside - you'll loop your dataset just once.

    Second case gives you two loops (second works on limited dataset) but the code is much more readable and operations are separated (filtering / modifying data).