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, '#' );
So according to the docs, here "callback" is getReverse() function, "initialValue" is '#'.
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.
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!
Top comments (0)