user2024080
user2024080

Reputation: 5099

What is the correct way to filter and calculate a number from array of object

In angularjs, how to loop through the arrays and get a value from a respected label and count with each other and return the value?

example i have an array like this:

"contractorsList": [
            {
              "name": "KP/A995/29",
              "percent": 78
            },
            {
              "name": "KP/A574/69",
              "percent": 33
            },
            {
              "name": "KP/A520/30",
              "percent": 38
            },
            {
              "name": "KP/A787/57",
              "percent": 35
            },
            {
              "name": "KP/A850/75",
              "percent": 49
            },
            {
              "name": "KP/A374/17",
              "percent": 47
            },
            {
              "name": "KP/A962/40",
              "percent": 33
            }
          ]

here there is a field as percent, i would like to iterate across the objects and need to get the total value of the percent. ( adding each percent to gather)

what is the correct way to do this in angular.js

i tried like this, but i didn't get any value:

scope.totalContracts = $filter('filter')( contractorsList, {percent:!null});

//i assumed to get the total values as array, so that i can add.

Upvotes: 0

Views: 370

Answers (2)

shubham2102
shubham2102

Reputation: 26

You can try this solution:

var val=0;
angular.forEach(contractorsList, function(value, key) {
    if(value.name === "KP/A995/29"){
       val += value.percent;
    }
}, contractorsList);

I hope this help.

Detailed Explanation:
It is simple, having a global variable 'val' with value 0, and adding the percent of each iterated object, in the given 'contratorsList'(i.e. array of objects), while iterating through it using angularJs function forEach. Please check for forEach of angular in documentation link: docs.angularjs.org/api/ng/function/angular.forEach Also the last parameter can be omitted as it is just a context of the iterator function. Hope this clears your doubts!! –

Upvotes: 0

Anton Telesh
Anton Telesh

Reputation: 3842

var total = contractorsList.reduce(function(result, item) {
  return result + item.percent;
}, 0)

Upvotes: 5

Related Questions