DEV Community

Discussion on: ELI5 - "Map-filter-reduce"

Collapse
 
dmfay profile image
Dian Fay

Also important to note that both map and filter can be redundant if you're already using reduce. Your JavaScript example could be written like this:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const ans = numbers.reduce(function(total, num) {
  if (num % 2 === 0) { // replaces filter
    return total += num * num; // replaces map
  }

  return total;
});

Obviously this doesn't demonstrate what map and filter do, which is less useful from that perspective! The big deal about it is that it only makes one pass. This doesn't matter much with ten elements but with bigger collections it can save a lot of time.

Collapse
 
jbbn profile image
João Bueno

Totally agree Dian :)

Just to register another way to write the same, I would code like this:

const ans = numbers.reduce((total, num) => (
  num % 2 === 0 // replaces filter
    ? total + num * num // replaces map
    : total
))

Regards!