Problem Statement
What does the reduce method do?
Explanation
The reduce method executes a reducer function on each element, accumulating the results into a single value.
It takes a callback function with an accumulator and current value. The accumulator stores the accumulated result.
You can provide an initial value as the second argument. If not provided, the first array element is used.
Reduce is used for summing, finding max or min, flattening arrays, grouping data, or any operation that combines all elements.
It is one of the most powerful but also most complex array methods.
Code Solution
SolutionRead Only
const numbers = [1, 2, 3, 4, 5];
// Sum all numbers
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
// How it works:
// acc starts at 0 (initial value)
// 0 + 1 = 1
// 1 + 2 = 3
// 3 + 3 = 6
// 6 + 4 = 10
// 10 + 5 = 15
// Find maximum
const max = numbers.reduce((acc, num) => {
return num > acc ? num : acc;
}, numbers[0]);
console.log(max); // 5
// Count occurrences
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(count); // {apple: 3, banana: 2, orange: 1}
// Flatten array
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
console.log(flat); // [1, 2, 3, 4, 5, 6]
// Without initial value
const product = [2, 3, 4].reduce((acc, num) => acc * num);
console.log(product); // 24 (2 * 3 * 4)Practice Sets
This question appears in the following practice sets:
