DEV Community

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 w...
Collapse
 
dance2die profile image
Sung M. Kim • Edited

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.

Collapse
 
krofdrakula profile image
Klemen Slavič

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));
Collapse
 
sadarshannaiynar profile image
Adarsh

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.

Collapse
 
nikolicstjepan profile image
Nikolić Stjepan

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