JavaScript reduce() Method
Combine array elements into a single value. Master this powerful method for calculations, transformations, and aggregations.
What is reduce()?
The reduce() method processes each element in an array sequentially and returns a single accumulated value. It's perfect for calculating sums, products, or combining array elements into a new data structure.
Calculate Sum Using reduce()
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15This example shows how the reduce() method iterates through an array and accumulates values to calculate the total sum.
Syntax
JavaScript reduce() Syntax Explained
array.reduce((accumulator, currentValue, index, array) => {
// Return the updated accumulator
return accumulator;
}, initialValue);The reduce() method takes a callback function and an optional initial value. The callback updates the accumulator for each element in the array.
accumulator: The accumulated result carried through iterations
currentValue: The current element being processed
initialValue: The starting value for the accumulator (optional)
Common Use Cases
Sum an Array
Sum All Numbers in an Array with reduce()
const numbers = [10, 20, 30, 40];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 100Use reduce() to combine all numbers in an array and return the total sum.
Find Maximum Value
Find the Maximum Number Using reduce()
const numbers = [5, 2, 8, 1, 9, 3];
const max = numbers.reduce((acc, num) =>
num > acc ? num : acc
);
console.log(max); // 9This example compares each element and keeps the largest value in the accumulator.
Convert Array to Object
Convert an Array into an Object with reduce()
const arr = ['a', 'b', 'c'];
const obj = arr.reduce((acc, val, idx) => {
acc[idx] = val;
return acc;
}, {});
console.log(obj); // {0: 'a', 1: 'b', 2: 'c'}reduce() can transform arrays into objects by building key-value pairs during iteration.
Group Objects by Property
Group Array Objects by Property Using reduce()
const users = [
{ name: 'Alice', role: 'admin' },
{ name: 'Bob', role: 'user' },
{ name: 'Charlie', role: 'admin' }
];
const grouped = users.reduce((acc, user) => {
if (!acc[user.role]) acc[user.role] = [];
acc[user.role].push(user.name);
return acc;
}, {});
console.log(grouped);
// { admin: ['Alice', 'Charlie'], user: ['Bob'] }This example groups users based on their role by dynamically creating keys in the accumulator object.
Flatten an Array
Flatten Nested Arrays Using reduce()
const nested = [[1, 2], [3, 4], [5]];
const flat = nested.reduce((acc, arr) =>
acc.concat(arr), []
);
console.log(flat); // [1, 2, 3, 4, 5]reduce() can flatten arrays by concatenating each inner array into a single accumulator array.
Common Mistakes
❌ Forgetting Initial Value
Avoid Missing Initial Value in reduce()
const arr = [1, 2, 3];
const sum = arr.reduce((acc, num) => acc + num);
// If first element is not a number, you'll get an error!
// Better:
const sum = arr.reduce((acc, num) => acc + num, 0);If the initial value is not provided, reduce() uses the first array element as the accumulator, which can lead to unexpected errors.
❌ Forgetting to Return Accumulator
Always Return the Accumulator in reduce()
const arr = [1, 2, 3];
const sum = arr.reduce((acc, num) => {
acc + num; // Forgot return!
}, 0);
console.log(sum); // undefined
// Correct:
const sum = arr.reduce((acc, num) => acc + num, 0);The callback must return the updated accumulator; otherwise, the result becomes undefined.
FAQs
What happens if the array is empty?
reduce() Behavior with Empty Arrays
const empty = [];
console.log(empty.reduce((a, b) => a + b, 0)); // 0
console.log(empty.reduce((a, b) => a + b)); // TypeError!Calling reduce() on an empty array without an initial value throws a TypeError. Always provide a default value to avoid errors.
When to use reduce()?
Use reduce() when you need to combine multiple array elements into a single value or data structure.