使用自定义比较函数将两个对象数组合并到javascript中

时间:2016-03-03 21:40:07

标签: javascript arrays object merge sum

我有两个对象数组,如:

var A = [{title:"name1",count:5},{title:"name2",count:1},{title:"name3",count:3}];

var B = [{title:"name2",count:7},{title:"name3",count:2},{title:"name4",count:3},{title:"name5",count:8}];

我需要在一个数组中合并这两个数组,并在“title”属性相同时对返回数组中的“count”值求和: 最后一个答案必须是:

[{title:"name1",count:5},{title:"name2",count:8},{title:"name3",count:5},{title:"name4",count:3},{title:"name5",count:8}]

我该怎么办?

6 个答案:

答案 0 :(得分:1)

使用Array.concatArray.map函数的解决方案:

    var merged = A.concat(B), titles = [], result = [];

    merged.map(function(obj){
        if (titles.indexOf(obj.title) === -1) {
            titles.push(obj.title);
            result.push(obj);
        } else {
            result[titles.indexOf(obj.title)]['count'] += obj['count'];
        }
    });

    console.log(result);  // will output the expected array of objects

答案 1 :(得分:0)

此提案正在使用临时对象和Array#forEach()

进行合并和计数
  

forEach()方法每个数组元素执行一次提供的函数。

var arrayA = [{ title: "name1", count: 5 }, { title: "name2", count: 1 }, { title: "name3", count: 3 }],
    arrayB = [{ title: "name2", count: 7 }, { title: "name3", count: 2 }, { title: "name4", count: 3 }, { title: "name5", count: 8 }],
    result = function (array) {
        var o = {}, r = [];
        array.forEach(function (a) {
            if (!(a.title in o)) {
                o[a.title] = { title: a.title, count: 0 };
                r.push(o[a.title]);
            }
            o[a.title].count += a.count;
        });
        return r;
    }(arrayA.concat(arrayB));

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

答案 2 :(得分:0)

可以像https://jsfiddle.net/menm9xeo/

那样完成
var noMatch;

var A = [{title:"name1",count:5},{title:"name2",count:1},{title:"name3",count:3}];
var B = [{title:"name2",count:7},{title:"name3",count:2},{title:"name4",count:3},{title:"name5",count:8}];

//for each A, loop through B's. If a match is found combine the Counts in A.
for(var i=0;i<A.length;i++){
    for(var j=0;j<B.length;j++){
    if(A[i].title == B[j].title){
        A[i].count += B[j].count;
    }
  }
}

//find all B's that were not combined with A in the previous step, and push them into A.
for(var i=0;i<B.length;i++){
    noMatch = true;
    for(var j=0;j<A.length;j++){
    if(B[i].title == A[j].title){
        B[i].count += A[j].count;
      noMatch = false;
    }
  }
  if(noMatch){A.push(B[i]);}
}

答案 3 :(得分:0)

答案 4 :(得分:0)

您可以使用Array#forEachArray#some来获得结果

var M = A.concat(B)

var C = [];

M.forEach(function(a) {
    var index;
    if (C.some(function(c, i) { index = i; return a.title == c.title; })) {
        C[index].count += a.count;
    } else {
        C.push(a);
    }
});

console.log(C); // as you expect

答案 5 :(得分:0)

这是一个简单的3行答案(减去A / B变量);利用对象必须具有唯一键的事实

var A = [{title:"name1",count:5},{title:"name2",count:1},{title:"name3",count:3}];
var B = [{title:"name2",count:7},{title:"name3",count:2},{title:"name4",count:3},{title:"name5",count:8}];

var o = {};
A.concat(B).forEach(function(a){o[a.title] = o.hasOwnProperty(a.title)? o[a.title]+a.count: a.count});
var AB = Object.keys(o).map(function(j){ return {title:j,count:o[j]} });