Search code examples
javascriptarrayssum

Summing a 2D array by "group"


I have an array in the form

[
['16-24', 192081],
['16-24', 94452],
['16-24', 1055],
['25-34', 192081],
['25-34', 94452],
['25-34', 1055],
...
]

I have many items in the array that I'd like to reduce down to the unique left-hand entries. This is an example of what I'd like to reduce down to

[
['16-24', 287588],
['25-34', 287588],
...
]

Obviously the numbers here are a contrived example. I've looked into JavaScript's array reduce, but how can I use it to achieve this effect?


Solution

  • Use reduce() to sum and map() to change it to the format you want.

    var vals = [
    ['16-24', 192081],
    ['16-24', 94452],
    ['16-24', 1055],
    ['25-34', 192081],
    ['25-34', 94452],
    ['25-34', 1055]
    ];
    
    var temp = vals.reduce(function (obj, cur) {
        var total = obj[cur[0]] || 0;
        obj[cur[0]] = total + cur[1];
        return obj;
    }, {} );
    
    var result = Object.keys(temp).map( function (key) { return [key, temp[key]]; });
    console.log(result);