如何合并包含对象的数组?

时间:2016-09-08 14:47:19

标签: javascript arrays sorting object

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



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




3 个答案:

答案 0 :(得分: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)




答案 1 :(得分:1)

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

答案 2 :(得分:0)

如果您愿意接受,那么请查看underscorejs,这对于使用Arrays和对象来说是一个很棒的实用工具。这将允许您编写灵活且透明的逻辑。文档也很好。

&#13;
&#13;
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());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;
&#13;
&#13;