The reduce() method is used to apply a function to each element in the array to reduces the array to a single value.
The reduce() method executes a reducer function on each element of the array (from left-to-right). and return value of the function is stored in an accumulator (result/total).
Note:The reduce() method does not change the original array.
array.reduce(callback, initialValue); OR array.reduce(function(accumulator, currentElement, currentIndex, array), initialValue)
| Parameter | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| function(accumulator, currentElement, currentIndex, array) |
|
||||||||
| initialValue | Optional. Initial value passed to the function , |
| Return | : | The single value |
|---|---|---|
| Version | : | ECMAScript 5 (ES5) |
Sum all the values of an array
var numbersArary = [2,5,6];
var newResultValue = numbersArary.reduce(testFunc,0)
function testFunc(accumulator,number) {
return accumulator + number;
}
console.log(newResultValue);
//Output : 13
Get the sum of array values by reduce() method using arrow function
const numbersArary = [2,5,6]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 2 + 5 + 6 console.log(numbersArary.reduce(reducer)); // Output : 13 // 3 + 2 + 5 + 6 console.log(numbersArary.reduce(reducer, 3)); // expected output: 16
const initialValue = 0;
const persons = [
{ id: 10, name: 'Vishal Gupta', age:20},
{ id: 11, name: 'Harsendra Singh', age:25},
{ id: 12, name: 'Vipin Katiyar', age:28},
{ id: 13, name: 'Umesh Yadav', age:29}
];
let sumIds = persons.reduce(function (accumulator, currentValue) {
return accumulator + currentValue.age;
}, initialValue);
console.log(sumIds);
//output : 102