Lets REDUCE the JavaScript Arrays.

Shreyas Kumar

Understanding how javascript array method reduce works.

I have been a fan of map and filter but never bothered to look into how we can use reduce to simplify and minimise the lines of code. First let’s have a look at what the documentation says.

array.reduce( callback(accumulator, currentValue, currentIndex, arr), initialValue);
  • callback : to execute on each element in the array (except for the first, if no initialValue is supplied )
  • accumulator: It recieves the return value of the callback, its the value returned from the last invocation of callback or initialValue.
  • currentValue: Current value of the array being processed.
  • currentIndex: Index of the current value of the array.
  • arr: The entire array on which we are calling reduce.
  • initialValue: Value as a first argument to call the callback for the first time.

Here is a small snippet to reverse a string using reduce method. We will loop through the code and dig deeper to see how it works.

// Reverse a string

var stringToReverse= "fiction";
var arrList = stringToReverse.split('');
// ["f", "i", "c", "t", "i", "o", "n"]
var getReverse = function(total, currentValue, currentIndex, arr) {
let valueToBeReturned = currentValue+total;
return valueToBeReturned;
}
var b = arrList.reduce(getReverse, '#');

So according to the docs, here “callback” is getReverse() function, “initialValue” is ‘#’.

iteration 1

First iteration of the loop.
first iteration

As we run the code ,

accumulator gets a value: ‘#’ this is the initial value that I have passed to the reduce method.

currentValue : ‘f’ // first element of the array.

valueToBeReturned: Its just concatenated value of currentValue and accumulator. (‘f#’ ).

lets see what next.

second iteration
third iteration
fourth iteration
fifth iteration
sixth iteration
last iteration

Here is the shortened code.

var stringToReverse= "fiction";var arrList = stringToReverse.split(''); 
// ["f", "i", "c", "t", "i", "o", "n"]
var getReverse = (reverse, currentValue) => currentValue+reverse;var reversedStr = arrList.reduce(getReverse, '');

Thats it folks. How about you go further and share about what happens if we don’t pass the “initialValue” ? what does accumulator gets in that case ?

Also , feedback would be valuable.

Cheers!

Shreyas Kumar

Written by

I'm a JavaScript developer.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade