Demystifying Array.reduce(): How to understand it and when to use it in your code

Nicky Hajal on September 19, 2018

ES5 and later versions of JavaScript brought several new methods for handling arrays. Many of them have become the best practice for common tasks... [Read Full]
markdown guide
 

My favorite is a pipe method.

const pipeOnce = (fn1, fn2) => (args) => (fn2(fn1(args)));
const pipe = (...ops) => ops.reduce(pipeOnce);
// OR const pipe = (...ops) 
//     => ops.reduce((fn1, fn2) => (args) => (fn2(fn1(args))));

const addTwo = a => a + 2;
const mulTwo = a => a * 2;

const addTwoMulTwo = pipe(addTwo, mulTwo);
console.log(addTwoMulTwo(1));  // (1 + 2) * 2 => 6
console.log(addTwoMulTwo(2));  // (2 + 2) * 2 => 8
console.log(addTwoMulTwo(3));  // (3 + 2) * 2 => 10

It's just amazing that you can not only pass an array of objects, you can pass an array of functions, as a function is a first-class citizen in JavaScript.

And also, C# has a reduce method named Aggregate, which I think reflects more of what it does.

 

Nice post. I have seen people using map to do something that can be easily done by reduce. But somehow I felt some developers don't know that reduce exists in the prototype of Array or they are hesitant to switch to reduce.

 

I like to use reduce when transforming lists, like creating a Map from an array based on a key:

const userData = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];

// a general-purpose array-to-map utility
const arrayToMap = (list, idMapper) =>
  list.reduce(
    (map, next) => {
      map.set(idMapper(next), next);
      return map;
    },
    new Map()
  );

console.log(arrayToMap(userData, user => user.id));
 

Yea, reduce is currently underrated for sure.
Great article, thanks Nicky for sharing!

 

Nice, I've used it here and there myself without fully understanding it. A good clear explanation, thanks!

code of conduct - report abuse