【问题标题】:merging two array of objects with custom compare function with javascript使用javascript将两个具有自定义比较功能的对象数组合并
【发布时间】:2016-06-17 10:52:22
【问题描述】:

我有两个对象数组,例如:

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}]

我该怎么做???

【问题讨论】:

  • 您没有提出问题,也没有尝试过。这就像我在说“我需要一辆法拉利”。我需要为它工作;)
  • 这不是 StackOverflow 的工作方式。请阅读帮助部分并提供您解决问题的尝试。

标签: javascript arrays object merge sum


【解决方案1】:

您可以使用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

【讨论】:

  • 请提供一些文本来为您的代码提供一些上下文。
  • @Suever 我已经添加了一些链接,剩下的代码很简单
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    可以这样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]);}
    }
    

    【讨论】:

      【解决方案4】:

      这是一个简单的 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]} });
      

      【讨论】:

        【解决方案5】:

        此提案正在与临时对象和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>');

        【讨论】:

          【解决方案6】:

          使用lodash._concat函数:

          var result = _.concat(A, B);
          

          Fiddle

          【讨论】:

            猜你喜欢
            • 2016-05-07
            • 2019-01-06
            • 1970-01-01
            • 1970-01-01
            • 2012-09-03
            • 2010-12-18
            • 2017-01-02
            • 2020-08-11
            • 1970-01-01
            相关资源
            最近更新 更多