Summing a 2D array by quot;groupquot;(通过“组对二维数组求和)
问题描述
我在表单中有一个数组
[
['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 的数组 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);
这篇关于通过“组"对二维数组求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过“组"对二维数组求和


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01