reduce
reduce (pure)
Reduces the array to a single value using a function that takes an accumulator and the current element of the array as parameters. This function instructs how the current element must be merged into the accumulator and returns the accumulator that will be used on the next iteration.
let arr = [1, 2, 3, 4];
// Get the sum of elements
arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
// => 10
// Classify the numbers by whether they are odd or not
arr.reduce(
(accumulator, currentValue) => {
if (currentValue % 2 === 0) {
accumulator.even.push(currentValue);
} else {
accumulator.odd.push(currentValue);
}
return accumulator;
},
{ even: [], odd: [] }
);
// => { even: [2, 4], odd: [1, 3] }
Backlinks