0

Below is a sample array of objects :

[{Name : Deji, Age: 12}, {Name : Sonia, Age 13}, {Name : Fabio, Age: 21}]

How do I iterate through the arrays in such a way as to add up the ages of the people in the array.

Is there a function that can add up the ages of the player?

Deji James
  • 367
  • 6
  • 20

4 Answers4

3

Use Array#forEach and Array#reduce to iterate over array items and add the age of each player to your variable.

forEach

const players = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age: 13}, {Name : 'Fabio', Age: 21}];

let age = 0;

players.forEach(player => age += player.Age);

console.log(age);

reduce

const players = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age: 13}, {Name : 'Fabio', Age: 21}];

const age = players.reduce((sum, player) => sum + player.Age, 0);

console.log(age);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

var players = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age : 13}, {Name : 'Fabio', Age: 21}];
var age = 0;
players.forEach(function(el){
 age+=el.Age;
})
console.log(age)

Loop through each object using forEach , get the element and access Age property, and add it.

Durga
  • 15,263
  • 2
  • 28
  • 52
1

First of all your JSON is not a valid one, it should be,

[ { "Name": "Deji", "Age": 12 }, { "Name": "Sonia", "Age": 13 }, { "Name": "Fabio", "Age": 21 } ]

With angularjs you can juse use array.reduce function to calculate the total.

DEMO

 angular.module('MyModule', [])
.controller( 'MyController', function($scope){
 $scope.data = [
  {
    "Name": "Deji",
    "Age": 12
  },
  {
    "Name": "Sonia",
    "Age": 13
  },
  {
    "Name": "Fabio",
    "Age": 21
  }
];    
$scope.sum = function(items, prop){
        return items.reduce( function(a, b){
            return a + b[prop];
        }, 0);
};
$scope.totalAges = $scope.sum($scope.data, 'Age');
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='MyModule' ng-controller='MyController'>
    <p>totalAges = {{totalAges}}</p>
</div>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

try this

var a = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age : 13}, {Name : 'Fabio', Age: 21}];

var sum = 0;
for(var i of a){

sum += i.Age;

}

console.log(sum);
Arun Kumaresh
  • 6,211
  • 6
  • 32
  • 50