通过“组"对二维数组求和

编程入门 行业动态 更新时间:2024-10-18 20:29:39
本文介绍了通过“组"对二维数组求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在表单中有一个数组

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

更多推荐

通过“组"对二维数组求和

本文发布于:2023-11-29 21:36:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!