Introduction
The reduce method helps you combine all items in a list into one value. It makes adding, multiplying, or merging easy.
The reduce method helps you combine all items in a list into one value. It makes adding, multiplying, or merging easy.
array.reduce((accumulator, currentValue) => {
// combine accumulator and currentValue
return newAccumulator;
}, initialValue);accumulator holds the combined result so far.
currentValue is the current item from the array.
const sum = [1, 2, 3].reduce((acc, val) => acc + val, 0);
const product = [2, 3, 4].reduce((acc, val) => acc * val, 1);
const sentence = ['Hello', 'world'].reduce((acc, val) => acc + ' ' + val, '').trim();
This program adds all numbers in the array and prints the total.
const numbers = [5, 10, 15]; const total = numbers.reduce((acc, val) => acc + val, 0); console.log('Total:', total);
If you skip the initialValue, reduce uses the first array item as the start.
Reduce works on arrays only.
Reduce combines array items into one value.
It uses a function with an accumulator and current value.
You can use it to add, multiply, join, or count items.
reduce method do in JavaScript?reduce on an array arr to sum its elements (safe for empty arrays)?const numbers = [1, 2, 3, 4]; const result = numbers.reduce((acc, val) => acc * val, 1); console.log(result);
const arr = [2, 4, 6]; const sum = arr.reduce((acc, val) => acc + val); console.log(sum);
const sales = [
{ product: 'A', amount: 10 },
{ product: 'B', amount: 20 },
{ product: 'A', amount: 15 }
];
// Use reduce to find total sales amount for product 'A'Pass the test and this pattern moves unknown