Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values of same Id in a Json Array using JS

I have a json array with Id and age as follows

var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];

I want to get sum of age which belong to same id which will be as follows

1 = 20
2 = 50
3 = 20
5 = 10

Please find the below code

$scope.TestFunc = function()
{
var tot = 0;
var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];
for(var i=0; i <arrayVal.length; i++ )
{
  for(var j=1; j<arrayVal.length - i; j++ )
  {
    if(arrayVal[i].id == arrayVal[j].id)
    {
      tot = arrayVal[i].age.valueOf() + arrayVal[j].age.valueOf();
    }
    else{
      tot = tot + arrayVal[i].age;
    }
  }
}
console.log("-----total----"+tot);
}

I don't receive the expected output. the console shows the output as 202020. What has gone wrong in the above code?

like image 823
tharindu Avatar asked Nov 21 '25 10:11

tharindu


1 Answers

With a simple reduce() operation:

const array = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];

const ages = array.reduce((a, {id, age}) => (a[id] = (a[id] || 0) + +age, a), {});

console.log(ages);

Besides the reduce solution being more compact and declarative, the main problem with the code provided is due to coercion. One of the age values has the string "20", forcing the subsequent + operations to be interpreted as string concatenation.

This answer avoids this unexpected side-effect using the +age, forcing age to be a Number (this could be made explicit by doing Number(age) instead).

like image 140
Robby Cornelissen Avatar answered Nov 23 '25 23:11

Robby Cornelissen