Javascript合并2个数组并对相同的键值求和

Javascript merge 2 arrays and sum same key values(Javascript合并2个数组并对相同的键值求和)

本文介绍了Javascript合并2个数组并对相同的键值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个数组:

    var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
    var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];

想要得到 1 个合并后的数组,对应键的总和;

Want to get 1 merged array with the sum of corresponding keys;

    var array1 = [[1,10],[2,10],[3,10],[4,10],[5,50],[6,50],[7,10],[8,10],[9,10]];

两个数组都有唯一的键,但是对应的键需要相加.

Both arrays have unique keys, but the corresponding keys needs to be summed.

我尝试了循环、concat 等,但无法得到我需要的结果.

I tried loops, concat, etc but can't get the result i need.

以前有人做过吗?

推荐答案

这是一种方法:

var sums = {}; // will keep a map of number => sum

// for each input array (insert as many as you like)
[array1, array2].forEach(function(array) {
    //for each pair in that array
    array.forEach(function(pair) {
        // increase the appropriate sum
        sums[pair[0]] = pair[1] + (sums[pair[0]] || 0);
    });
});

// now transform the object sums back into an array of pairs
var results = [];
for(var key in sums) {
    results.push([key, sums[key]]);
}

查看实际操作.

这篇关于Javascript合并2个数组并对相同的键值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Javascript合并2个数组并对相同的键值求和

基础教程推荐