Array.prototype.reduce's initial value is optional
- Published at
- Updated at
- Reading time
- 2min
reduce()
is one of these underrated Array methods that can be tremendously useful to accumulate array items. Define an initial value, iterate over all array items and define a callback function to form a combined result.
The beauty: each callback's return value is provided to the next entry callback so that you can sum numbers or regroup the array entries inside of an object.
reduce((previousValue, currentValue) => {
/* ... */
});
reduce((previousValue, currentValue, currentIndex) => {
/* ... */
});
reduce((previousValue, currentValue, currentIndex, array) => {
/* ... */
});
reduce((previousValue, currentValue, currentIndex, array) => {
/* ... */
}, initialValue);
And after all these years, looking at these reduce
callback signatures, I discovered that the initial value is optional. π²
Here's an example of summing numbers.
// sum all numbers in the array
// start with `0`
[1, 2, 3, 4, 5].reduce((previousValue, currentValue) => {
console.log(previousValue);
// the return value will be the next `previousValue`
return previousValue + currentValue;
}, 0); // 15
// Output in the console:
// 0
// 1
// 3
// 6
// 10
// 15
You might ask if the first iteration starting with 0
is necessary. And you're correct β it's redundant and is a case for not providing an initial value at all!
// sum all numbers in the array
// start with `1`
[1, 2, 3, 4, 5].reduce((previousValue, currentValue) => {
console.log(previousValue);
// the return value will be the next `previousValue`
return previousValue + currentValue;
}); // 15
// Output in the console:
// 1
// 3
// 6
// 10
// 15
Without a second argument, the reduce
loop starts with the first array entry instead of an initial value β ergo, you'll save one iteration! π
This is a nifty little find! Big thanks to RamΓ³n, who tweeted this tip!
If you want to learn more about the array method, head over to the reduce
entry on MDN.
Join 5.5k readers and learn something new every week with Web Weekly.