skip to Main Content

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


  1. Just fix your line:

    total_byID[id] = (total_byID[id] ?? 0) + +value;
    

    Here if a sum with an id doesn’t exist yet, you start with 0, if you use += you are adding to undefined thus resulting in NaN.

    And also change total_byID to object, since your keys aren’t real sequential numbers but strings.

    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] = (total_byID[id] ?? 0) + +value;
        })
    })
    console.log(total_byID)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    Login or Signup to reply.
    1. If you’re storing key/values it’s generally better to use an object (or a Map) rather than an array to spare ambiguity.

    2. You need to initialise your property values to zero. You can’t add things to undefined.

    3. Your object values are currently strings. You need to coerce them to numbers to perform the addition.

    const 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"}];
    
    // Use an object
    const total_byID = {};
    
    $.each(myarray, function(index, item) {
      $.each(item, function(id, value) {
    
        // If the key doesn't exist create it and set its
        // value to zero
        total_byID[id] ??= 0;
    
        // Add the coerced number to the current
        // property value
        total_byID[id] += Number(value);
      });
    });
    
    console.log(total_byID);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search