0

I'm learning the reduce method and I am trying to use it on this array of objects but i cant seem to figure it out here. the objective is to add all of the age elements together, I can do it with a for loop, but I cant seem to figure it out how to achieve the same with a reduce() method.

let array1 = [
  {
   "name": 'Neo',
   "age":'28',
   "fav Food": "Sea Food"
  },
  {
   "name": 'Charlie',
   "age":'20',
   "fav Food": "Sushi"
  },
  {
   "name": 'Benjamin',
   "age":'21',
   "fav Food": "Asian"
  },
  {
   "name": 'Martha',
   "age":'47',
   "fav Food": "Italian"
  }
]

I want to transform this for loop into a reduce method.

let sum=0;
for (let i = 0; i<array1.length;i++){
  sum += parseInt(array1[i].age);
}

so far I have this but its not working, any help would be greatly appreciated.

const sum2 = array1.reduce( (accumulation, item) => {
return accumulation += (item = parseInt(array1[0].age));
},0 );
Sascha
  • 4,576
  • 3
  • 13
  • 34
  • `return accumulation += parseInt(item.age)` – Nick Jul 30 '20 at 08:17
  • Thanks man! I can sleep sound now :) if anyone is looking for the final code solution its: const sum2 = array1.reduce( (accumulation, item) => { return accumulation += parseInt(item.age); },0 ); – Robert Rodriguez Jul 30 '20 at 08:20

3 Answers3

3

You need to access age of item.

let array = [{ name: 'Neo', age: '28', 'fav Food': 'Sea Food' }, { name: 'Charlie', age: '20', 'fav Food': 'Sushi' }, { name: 'Benjamin', age: '21', 'fav Food': 'Asian' }, { name: 'Martha', age: '47', 'fav Food': 'Italian' }],
    sum = array.reduce((sum, item) => sum += +item.age, 0);

console.log(sum);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

item is already the current item, so you shouldn't assign to it.

accumulation += (item = parseInt(array1[0].age))

becomes

accumulation + parseInt(item.age)
Buh Buh
  • 7,443
  • 1
  • 34
  • 61
0

 let array1 = [ { "name": 'Neo', "age":'28', "fav Food": "Sea Food" }, { "name": 'Charlie', "age":'20', "fav Food": "Sushi" }, { "name": 'Benjamin', "age":'21', "fav Food": "Asian" }, { "name": 'Martha', "age":'47', "fav Food": "Italian" } ]  
  res=array1.reduce((acc,curr) => acc += Number(curr.age) , 0)
  console.log(res)
Sven.hig
  • 4,449
  • 2
  • 8
  • 18