-4

I have an array of Objects and I would like to put numbers together in a specific field in those Objects. The Age field in each object.

this is what I did :

var users = [{name:'John',age:36},{name:'Max',age:21}]


var counter = 0;
var example = users.forEach(function(user){
counter += user.age
})
Bar Levin
  • 205
  • 1
  • 12
  • 1
    ok, so what is the issue? – AT82 Aug 14 '19 at 11:38
  • could you add a sample of the array containing the user data so we can create code snippets to create working examples? – RainyRain Aug 14 '19 at 11:40
  • 1
    Possible duplicate of [Better way to sum a property value in an array](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array) – Mihir Aug 14 '19 at 11:53

2 Answers2

2

You can use reduce like that

let sum = users.reduce((a,b) => a.age + b.age, 0);
ahmeticat
  • 1,899
  • 1
  • 13
  • 28
1

You can use simple for loop:

var users = [
  {
    age: 22
  },
  {
    age: 25
  },
  {
    age: 70
  }
];

var ageSum = 0;

for (var i = 0; i < users.length; i++) {
  ageSum += users[i].age;
}

console.log(ageSum);

Sai
  • 44
  • 2