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 );
2
  • return accumulation += parseInt(item.age) Commented Jul 30, 2020 at 8: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 ); Commented Jul 30, 2020 at 8:20

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.