3

I have a json response that returns an array. From the array I want to calculate the total of a variable in the json array. here is a snippet

    $rootScope.getData = function () {
                $http({ 
                method: 'GET',
    ....
    console.log(JSON.stringify(res.data.data));

    returns

    [{
    "name":"John",
    "age":30
    }
{
    "name":"Doe",
    "age":30
    }]

how to calculate the total age in the array to get 60 is a challenge

1
  • 1
    Please share the code which you have tried. Commented Nov 23, 2018 at 17:21

5 Answers 5

3

Use a fold/reduce

res.data.data.reduce(function (total, person) {
  return total + person.age;
}, 0);
Sign up to request clarification or add additional context in comments.

Comments

2
   $scope.data =   [{
        "name":"John",
        "age":30
        },
    {
        "name":"Doe",
        "age":30
        }]

  $scope.sum = 0;
angular.forEach($scope.data, function(value, key){
  $scope.sum += value.age
})

plunker: http://plnkr.co/edit/tpnsgeAQIdXP4aK8ekEq?p=preview

Comments

2
let sum = 0;
res.data.data.forEach((element) => {
    sum += element.age;
});
// done!

Comments

1

Try a for..of loop:

let arr = [{
    "name": "John",
    "age": 30
  },
  {
    "name": "Doe",
    "age": 30
  }
];

let sum = 0;


for (let el of arr) {
  sum += el.age;
}

console.log(sum);

for..of iterates over every element of an array (or any other iterable). Then you can easily sum up the total (here stored in the sum variable).

Comments

0

var data = [{
    "name":"John",
    "age":30
    },
    {
    "name":"Doe",
    "age":30
    },
    {
    "name":"Doe",
    "age":10
    }
    ]
    
    
    var totalAge = data.map((person)=> person.age)// get the age values
                        .reduce((sum, current)=> sum+ current) // sum the age values
    
    console.log(totalAge)
    
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.