且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按“组"对二维数组求和

更新时间:2023-11-12 08:01:22

使用 reduce() 求和和 map() 将其更改为您想要的格式.

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]] = 总数 + cur[1];返回对象;}, {} );var result = Object.keys(temp).map( function (key) { return [key, temp[key]]; });控制台日志(结果);

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 I'm unsure how to use it to achieve this effect

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);