通过“分组"对2D阵列求和. [英] Summing a 2D array by "group"

查看:61
本文介绍了通过“分组"对2D阵列求和.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,形式为

[
['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],
...
]

显然,这里的数字是一个虚构的示例.我已经研究了javascript的array reduce,但是不确定如何使用它来实现这种效果.

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

推荐答案

使用 reduce()求和,并 map()将其更改为所需的格式.

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

这篇关于通过“分组"对2D阵列求和.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆