JavaScript array reduce() method used to execute a reducer function for the array element. The final result of running the reducer across all elements of the array is a single value.
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Note: It does not execute the function for empty array elements and does not change the original array.
JavaScript array reduce
Simple example code Sum of All Values of Array.
<!DOCTYPE html>
<html>
<body>
<script>
const numbers = [1, 2, 3, 4, 5, 6];
function sum(accumulator, currentValue) {
return accumulator + currentValue;
}
let res = numbers.reduce(sum);
console.log(res);
</script>
</body>
</html>
Output:
Using the arrow function for same example
let summation = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
console.log(summation); // 21
Typically, we use a for
loop to iterate over the elements and add them up as shown in the following example:
let numbers = [1, 2, 3];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum); //6
More JavaScript Array reduce() examples
Suppose that you have the following shoppingCart
array of product objects:
let shoppingCart = [
{
product: 'phone',
qty: 1,
price: 500,
},
{
product: 'Screen Protector',
qty: 1,
price: 10,
},
{
product: 'Memory Card',
qty: 2,
price: 20,
},
];
To calculate the total amount of products in the shopping cart, you can use the reduce()
method, like this:
let total = shoppingCart.reduce(function (previousValue, currentValue) {
return previousValue + currentValue.qty * currentValue.price;
}, 0);
Output: 550
Do comment if you have any doubts or suggestions on this JS array method.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version