A method that reduces an array of values into a single returned value after processing it.
Unlike filter and map, reduce takes at least two arguments; a callback and an initial value. The callback function also takes two parameters; an accumulator and the current processed array value.
If an initial value for the accumulator is not given, reduce()
will take the first element of the array and use it as the initial value.
let sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
return accumulator + currentValue
}, 0)
// sum is 6
Alternatively written with an arrow function:
let total = [ 0, 1, 2, 3 ].reduce(
( acc, cur ) => acc + cur,
0
);
Example
Return the total of all prices
const prices = [6.75, 3.10, 4.00, 8.12]; // Total: 21.97
let total = 0;
prices.forEach(price => {
total += price;
});
console.log(total);
Using reduce()
const prices = [6.75, 3.10, 4.00, 8.12]; // Total: 21.97
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);
Example
Return a count of the names that begin with the letter G.
const names = ['Gary', 'Pasan', 'Gabe', 'Treasure', 'Gengis', 'Gladys', 'Tony'];
const gNameCount = names.reduce((count, name) => {
if(name[0] === 'G') {
return count + 1;
}
return count;
}, 0);
console.log(gNameCount);
Example
Return the total phone numbers with a 503 area code.
const phoneNumbers = ["(503) 123-4567", "(646) 123-4567", "(503) 987-6543", "(503) 234-5678", "(212) 123-4567", "(416) 123-4567"];
let numberOf503;
numberOf503 = phoneNumbers.reduce((count, num) => {
if(num.substring(1,4) === '503') {
return count + 1;
}
return count;
} ,0);
// numberOf503 should be: 3