0

我有两个包含一些对象的数组,我需要知道如何组合它们并排除任何重复项。(例如,apple: 222如果第二个数组中包含的对象已经存在于第一个数组中,则应该排除它。)

检查以下:

var arr1 = [
    {apple: 111, tomato: 55},
    {apple: 222, tomato: 55}
]

var arr2 = [
    {apple: 222, tomato: 55},
    {apple: 333, tomato: 55}
]

我希望结果是这样的:

   var res = [
    {apple: 111, tomato: 55},
    {apple: 222, tomato: 55},
    {apple: 333, tomato: 55}
]

我怎么能在javascript中做到这一点?

4

2 回答 2

1

您可以编写重复数据删除功能。

if (!Array.prototype.dedupe) {
  Array.prototype.dedupe = function (type) {
    for (var i = 0, l = this.length - 1; i < l; i++) {
      if (this[i][type] === this[i + 1][type]) {
        this.splice(i, 1);
        i--; l--;
      }
    }
    return this;
  }
}

function combine(arr1, arr2, key) {
  return arr1
    .concat(arr2)
    .sort(function (a, b) { return a[key] - b[key]; })
    .dedupe(key);   
}

var combined = combine(arr1, arr2, 'apple');

小提琴

于 2013-10-16T11:24:16.300 回答
1

此解决方案是否符合您的需求(演示)?

var res, i, item, prev;

// merges arrays together
res = [].concat(arr1, arr2);

// sorts the resulting array based on the apple property
res.sort(function (a, b) {
    return a.apple - b.apple;
});

for (i = res.length - 1; i >= 0; i--) {
    item = res[i];

    // compares each item with the previous one based on the apple property
    if (prev && item.apple === prev.apple) {

        // removes item if properties match
        res.splice(i, 1);
    }
    prev = item;
}
于 2013-10-21T16:37:51.277 回答