reduce method in javascript array of bjects 1

reduce method in javascript array of bjects

var objs = [
  {name: "Peter", age: 35},
  {name: "John", age: 27},
  {name: "Jake", age: 28}
];

objs.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue.age;
}, 0); // 35 + 27 + 28 = 90

Here is what the above code is Doing:
1. The reduce() method is called on the objs array.
2. The callback function takes two arguments: accumulator and currentValue.
3. The accumulator is the total of all the ages.
4. The currentValue is the current object being processed.
5. The callback function returns the sum of accumulator and currentValue.age.
6. The 0 is the initialValue.
7. The reduce() method returns the sum of all the ages, which is 90.

Similar Posts