Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...