The reduce method in JavaScript is used to “reduce” an array to a single value, which can be anything—a number, an object, another array, etc. It accepts a reducer function that will get executed on all the items of the specified array in the left-to-right. The returned single value is stored in the accumulator
Syntax
array.reduce((accumulator, currentValue, index, array) => {
// Logic to reduce the array
}, initialValue);
Parameters
- accumulator: This holds the accumulated result of the function so far.
- currentValue: The current element being processed in the array.
- index (optional): The index of the current element.
- array (optional): The array on which
reducewas called.
In this article, we’ll explore five examples to illustrate how reduce works –
Find the Maximum Value
const numbers = [5, 2, 9, 1, 5, 6];
// Initialize the accumulator with an object containing initial min and max values.
const minMax = numbers.reduce((acc, current) => {
if (current < acc.min) acc.min = current;
if (current > acc.max) acc.max = current;
return acc;
}, { min: numbers[0], max: numbers[0] });
console.log("Minimum:", minMax.min);
console.log("Maximum:", minMax.max);This reduce call initializes with an object holding min and max properties. As it iterates, it updates min and max whenever a lower or higher value is found.
The sum of All Elements in an Array
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue; // Add the current value to the accumulator
}, 0);
console.log(sum); // Output: 15Here, reduce starts with 0 as the initial accumulator value and adds each element to it sequentially, giving the total sum at the end.
Flattening Nested Arrays
const arr = [1, [2, [3, [4]], 5]];
const flatten = (array) =>
array.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []);
console.log(flatten(arr)); // [1, 2, 3, 4, 5]This recursive function checks if each element is an array; if so, it flattens it further by calling flatten again. The reduce function concatenates values into a single array, effectively removing nesting.
Filtering Falsy Values from an Array
const array = [0, 1, false, 2, '', 3, null, 4, undefined, 5, NaN];
const filteredArray = array.reduce((acc, curr) => {
if (Boolean(curr)) {
acc.push(curr);
}
return acc;
}, []);
console.log(filteredArray); // Output: [1, 2, 3, 4, 5]This example uses Boolean(curr) to test each item. If it’s true, it’s added to acc, the array that holds the filtered values.
Counting Occurrences of Items in an Array
const array = ['apple', 'banana', 'orange', 'apple', 'orange', 'banana', 'apple'];
const countOccurrences = array.reduce((accumulator, currentValue) => {
// Check if the current value already exists in the accumulator
if (accumulator[currentValue]) {
accumulator[currentValue]++;
} else {
accumulator[currentValue] = 1;
}
return accumulator;
}, {});
console.log(countOccurrences);
// Output: { apple: 3, banana: 2, orange: 2 }Here, reduce checks if the current item already has a key in the accumulator object. If it does, it increments the count; if not, it sets the count to 1.
Wrapping Up
The reduce method in JavaScript can do much more than just sum numbers. It can help find values, flatten arrays, filter elements, and even count occurrences—all in a single pass. Understanding reduce gives you a powerful tool for handling complex array transformations cleanly and efficiently.
