【问题标题】:how to merge arrays which contains objects?如何合并包含对象的数组?
【发布时间】:2017-01-16 13:36:12
【问题描述】:

我有两个以上的数组,其中的对象具有一些相似的属性, 我想将所有数组合并为一个数组并将主题排序如下:

array = [ 
 [ { "name" : "Jack", count: 10 }, { "name": "Fred", "count": 20 } ],
  [ { "name": "Jack", count: 3 }, { "name": "Sara", "count": 10 } ]
]

merged_array = [
  { "name": "Fred", "count": 20 },
  { "name": "Jack", "count": 13 },
  { "name": "Sara", "count": 10 }
]

【问题讨论】:

  • 基于下划线的答案对您的问题有帮助吗?

标签: javascript arrays sorting object


【解决方案1】:

您可以使用两个forEach() 来获取包含合并对象的数组,然后使用sort() 对其进行排序。

var array = [
  [{
    "name": "Jack",
    count: 10
  }, {
    "name": "Fred",
    "count": 20
  }],
  [{
    "name": "Jack",
    count: 3
  }, {
    "name": "Sara",
    "count": 10
  }]
]

var result = [];
array.forEach(function(a) {
  var that = this;
  a.forEach(function(e) {
    if (!that[e.name]) {
      that[e.name] = e;
      result.push(that[e.name]);
    } else {
      that[e.name].count += e.count
    }
  })
}, {})

result.sort(function(a, b) {
  return b.count - a.count;
})

console.log(result)

【讨论】:

  • @SAlidadi 我在答案末尾添加了排序。
【解决方案2】:
array
 .reduce(function(result, arrayItem) {
   result = result || [];

   // sort also can be implemented here
   // by using `Insertion sort` algorithm or anyone else

   return result.concat(arrayItem);
 })
 .sort(function(a,b) { return a.count < b.count; })

【讨论】:

    【解决方案3】:

    如果您愿意,请查看underscorejs,它是处理数组和对象的绝佳实用程序。这将允许您编写灵活和透明的逻辑。文档也不错。

    var arrays = [
      [{
        "name": "Jack",
        count: 10
      }, {
        "name": "Fred",
        "count": 20
      }],
      [{
        "name": "Jack",
        count: 3
      }, {
        "name": "Sara",
        "count": 10
      }]
    ]
    
    var result = _.chain(arrays)
      .flatten()
      .union()
      // whatever is the "key" which binds all your arrays
      .groupBy('name')
      .map(function(value, key) {
    
          var sumOfCount = _.reduce(value, function(entry, val) {
            // the fields which will need to be "aggregated"
            return entry + val.count;
          }, 0);
    
          return {
            'name': key,
            'count': sumOfCount
          };
    
        }
    
      )
      // you can have your own sorting here
      .sortBy('count')
      .value();
    
    
    console.log(result.reverse());
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 2020-10-03
      相关资源
      最近更新 更多