I need to sum value of same id.
This is my code
var myarray = [
{"a25": "5000"},{"s36": "125"},{"d44": "15"},{"a25": "3500"},{"s36": "25"},{"d44": "164"},{"a25": "4500"},{"s36": "1251"},{"d44": "75"},{"a25": "251"},{"s36": "120"},{"d44": "94"},{"a25": "12515"}
];
var total_byID = [];
$.each(myarray, function(index, item){
$.each(item, function(id,value){
total_byID[id] += value;
})
})
console.log(total_byID)
bu the result is:
a25:"undefined50003500450025112515"
d44:"undefined151647594"
s36:"undefined125251251120"
I need an array like this:
[a25:25766,d44……..]
Can anyone help me?
I tried searching in many posts here, I tried both with parseFloat and parseInt, which even without anything, with the two parses, it returned NaN, without it, it returned undefined and the list of values
2
Answers
Just fix your line:
Here if a sum with an id doesn’t exist yet, you start with
0
, if you use+=
you are adding toundefined
thus resulting inNaN
.And also change
total_byID
to object, since your keys aren’t real sequential numbers but strings.If you’re storing key/values it’s generally better to use an object (or a
Map
) rather than an array to spare ambiguity.You need to initialise your property values to zero. You can’t add things to
undefined
.Your object values are currently strings. You need to coerce them to numbers to perform the addition.