How To Use Reduce() - Javascript Array.prototype.reduce()

How To Use Reduce() - Javascript Array.prototype.reduce()

As a JavaScript developer, array methods are among the most important concepts you need to master. Here we will talk about reduce() , a powerful array method, but it's common to see new JavaScript developers struggle to understand its concept. It's a bit difficult to understand and sometimes hard to read.





  • What is reduce() in JavaScript ?
  • How reduce work ?
  • When to use it ?
  • Tips and notes





What is Array.prototype.reduce() ?



The Array.prototype.reduce() is an iterative method used to call reducer function on every element of a given array.



Syntax:





// initial Value is optionnal Array.prototype.reduce((accumulator, currentValue, currentIndex, thisArray) => {/** */}, initialValue) function callback (accumulator, currentValue, currentIndex, thisArray) { /** */ } Array.prototype.reduce(callback, initialValue)

reduce(callback, initialValue) parameters



callback(accumulator, currentValue, currentIndex, array)



Reducer function executed for each element in the array. On the next call, the return value of this function becomes the accumulator, and on the last call, the return value will be the result of the reduce() function.



If no initial value is specified, the callback will not called for the array[0], the array[0] become the accumulator in the first call which begin at array[0]method



  • accumulator the accumulated value returned by the callback, if no initialValue is added the first element of the array become the initial value.
  • currentValue is the current element. Without initialValue, it's array[1] on the first call, otherwise array[0]
  • currentIndex index of the current element, Without initialValue, it's 1 on the first call, otherwise 0
  • array the array used to call the reduce() method





InitialValue (optional)



Used as the accumulator on the first call of the callback . If no value is passed here, the value of the first element is used as initialValue of the accumulator on the first call.





If the initialValue is omitted, the array[0] become the accumulator on the first call of the callback and the callback is not called against the array[0].
reduce() method is a concept of functional programming, it's not possible to mutate the accumulated value. A new accumulator must be return on every callback() call.

return value



The accumulated value of the reducer function (callback) on the last call.



You can think that the return value of the reduce() method is the return value of the last callback function
const arrayOfNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // calculate the sum of the element of the array const sumOf = arrayOfNumber.reduce( ( // acc is the current result accumulator, // current element of the array currentElement, // index of the current element _index, // the given array (here "arrayOfNumber") _thisArray ) => { return accumulator + currentElement; }, // initial value // initial value can be array, object, string, number etc 0 ); console.log(sumOf); // 45

How Reduce() Work ?



Well now, we will try to understand how it work under the wood. Let's take an example and we will watch what going on :

const arrayOfNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const howItWork = arrayOfNumber.reduce((accumulator, currentValue, index) => { console.log(`____________________${index}_____________________\n`); console.log(`___CurrentValue: ${currentValue}`); console.log(`___accumulator : ${accumulator}`); console.log(`___Current operation : ${accumulator} + ${currentValue} = ${accumulator + currentValue}\n`); return accumulator + currentValue; }, 0); console.log(howItWork); // 45 // how it work // ____________________0_____________________ // ___CurrentValue: 1 // ___accumulator : 0 // ___Current operation : 0 + 1 = 1 // ____________________1_____________________ // ___CurrentValue: 2 // ___accumulator : 1 // ___Current operation : 1 + 2 = 3 // ____________________2_____________________ // ___CurrentValue: 3 // ___accumulator : 3 // ___Current operation : 3 + 3 = 6 // ____________________3_____________________ // ___CurrentValue: 4 // ___accumulator : 6 // ___Current operation : 6 + 4 = 10 // ____________________4_____________________ // ___CurrentValue: 5 // ___accumulator : 10 // ___Current operation : 10 + 5 = 15 // ____________________5_____________________ // ___CurrentValue: 6 // ___accumulator : 15 // ___Current operation : 15 + 6 = 21 // ____________________6_____________________ // ___CurrentValue: 7 // ___accumulator : 21 // ___Current operation : 21 + 7 = 28 // ____________________7_____________________ // ___CurrentValue: 8 // ___accumulator : 28 // ___Current operation : 28 + 8 = 36 // ____________________8_____________________ // ___CurrentValue: 9 // ___accumulator : 36 // ___Current operation : 36 + 9 = 45 // ==> print result : 45

When to use reduce() ?



There are different situations you can use reduce() over other methods. But more you know how to use it the more you know when to use it.

Here are some example we use reduce method.





Grouping data of array:

// we will try to group odd and even number const arrayOfNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // Result we want // const group = { // odd: [1, 3, 5, 7, 9], // even: [2, 4, 6, 8], // }; // use reduce to group data const initialGroup = { odd: [], even: [], }; function callbackFn(acc, currentValue) { if (currentValue % 2) { return { ...acc, even: acc.even.concat(currentValue), }; } return { ...acc, odd: acc.odd.concat(currentValue), }; } const group = arrayOfNumber.reduce(callbackFn, initialGroup); console.log(group); // { odd: [ 2, 4, 6, 8 ], even: [ 1, 3, 5, 7, 9 ]

Here is an example without initial value:



Note that the currentValue begin in [1] (here 2) and index [1] (here 1)

const arrayOfNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const withoutInitialValue = arrayOfNumber.reduce((acc, currentValue, index) => { console.log( `Accumulator: ${acc}, current value: ${currentValue}, index: ${index}` ); return acc + currentValue; }); // Accumulator: 1, current value: 2, index: 1 // Accumulator: 3, current value: 3, index: 2 // Accumulator: 6, current value: 4, index: 3 // Accumulator: 10, current value: 5, index: 4 // Accumulator: 15, current value: 6, index: 5 // Accumulator: 21, current value: 7, index: 6 // Accumulator: 28, current value: 8, index: 7 // Accumulator: 36, current value: 9, index: 8 console.log(withoutInitialValue); // 45

Tips and notes



  • Always specified initialValue
  • The accumulated value is not mutable, see mutable object on MDN, see immutable on MDN
  • If no initialValue is specified, callback does not called against first element, array[0] become the accumulator on the first call



To learn more about reduce() method, this article from MDN is one the best article you need to read.



See on MDN: Javascript Reduce



Thanks for reading.



Please leave a comment if you appreciate my work. Tell me if there are improvement you want to mention or added here.


Avatar image

By Mahady Manana, Fullstack Javascript Developer

07 December 2022 at 15 h 33

"Skills are honed through the interplay of learning and teaching - one must learn in order to teach, and teach in order to truly learn”. As a passionate Javascript developer, I enjoy sharing my knowledge and skills with others, and regularly publish tutorials on my website and other platforms about the latest Javascript, Typescript, Node.js, React.js, Next.js and more to help others learn and stay up to date with the latest developments trends.