The reduce() method executes a provided function for each array value (from left to right), resulting in a single output value.
The syntax of the reduce() method:
array.reduce((accumulator, currentValue, index, array) => { ... }, initialValue)
For example, we have an array of numbers, and we want to sum the numbers:
// Using for loop
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum); // 15
// Using reduce
const numbers = [1, 2, 3, 4, 5]
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15
In the above example:
total
(accumulator) and num
(currentValue)callback iteration | accumulator | currentValue | return value |
---|---|---|---|
first call | 0 | 1 | 1 |
second call | 1 | 2 | 3 |
third call | 3 | 3 | 6 |
fourth call | 6 | 4 | 10 |
fifth call | 10 | 5 | 15 |
Flattening an array is to convert an array of arrays into a single array that contains all values. We can do so with reduce() method.
const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flatValues = data.reduce((total, value) => {
return total.concat(value);
}, []);
console.log(flatValues); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
We can use the spread operator to make it shorter:
const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flatValues = data.reduce(
(total, value) => [...total, ...value], []
);
console.log(flatValues); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
We can use push() and indexOf() with reduce() function to remove duplicates from the array.
const data = [1, 2, 3, 1, 4, 3, 3, 5, 5, 5, 8, 9];
const order = data.reduce((accumulator, value) => {
if (accumulator.indexOf(value) === -1) {
accumulator.push(value);
}
return accumulator;
}, []);
console.log(order); // [1, 2, 3, 4, 5, 8, 9]
For example, we have an order. We want to know the number of each dish in the order.
const order = ["chicken", "pizza", "burger", "pizza", "pizza", "chicken", "burger", "burger", "pasta"];
const order = dishes.reduce((total, dish) => {
const dishCount = total[dish];
dishCount ? (total[dish] = dishCount + 1) : (total[dish] = 1);
return total;
}, {});
console.log(order)
// {chicken: 2, pizza: 3, burger: 3, pasta: 1}