DEV Community

Cover image for JavaScript Reduce method
shrek-7
shrek-7

Posted on

JavaScript Reduce method

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 ( " make it difficult for others ").

This is 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 dive 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, '#' );
Enter fullscreen mode Exit fullscreen mode

So according to the docs, here "callback" is getReverse() function, "initialValue" is '#'.

  • first Iteration
    Iteration 1

  • 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
    Alt Text

  • third iteration
    Alt Text

  • fourth iteration
    Alt Text

  • fifth iteration
    Alt Text

  • sixth iteration
    Alt Text

*last iteration
Alt Text

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, '' );
Enter fullscreen mode Exit fullscreen mode

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!

MDN web docs

Top comments (0)