Reduce Javascript
- What is
Reduce()?reduce()is a method of theArrayobject.- It reduces an array of values down to just one value.
- More formally, it iterates over each element of the array and accumulates them into a single value.
- The final value of the accumulator, after iterating over all elements, is the return value of the
reduce()method.
array.reduce(callback(accumulator, currentValue, index, array), initialValue);
-
What is this used for?
- For performing operations like summing numbers, flattening arrays, or building objects from an array
-
What happens when
initialValueis not provided by the user?- then
accumulatoris initialized with the value of the first element of the array, in the first iteration. Refer Reduce Polyfill Javascript
- then
const nums = [1, 2, 3, 4];
let initialValue = 0;
const sum = nums.reduce((accumulator, current, index, originalArray) => {
return accumulator + current;
}, initialValue)
console.log(sum);