如何根据多个条件从数组中删除重复的对象

时间:2016-08-31 09:12:48

标签: javascript arrays arrayobject

我试图通过在对象内部放置多个字段来从数组中找到重复的对象。

我想比较对象的2个字段和同一个数组的其他对象。

我想在名字和lname中忽略我的对象中的第3个字段link

  values = [{
    name: 'newton',
    lname: 'king',
    link: '123'
  }, {
    name: 'tom',
    lname: 'kurtz',
    link: '123'
  }, {
    name: 'newton',
    lname: 'king',
    link: '456'
  }, {
    name: 'jan',
    lname: 'heckal',
    link: '123'
  }]

如何查找和删除具有如下输出的重复对象

  values = [{
    name: 'newton',
    lname: 'king',
    link: '123'
  }, {
    name: 'tom',
    lname: 'kurtz',
    link: '123'
  }, {
    name: 'jan',
    lname: 'heckal',
    link: '123'
  }]

1 个答案:

答案 0 :(得分:0)

这几乎与Remove duplicate objects from an array using javascript

重复



 var arrResult=[],
     arr = [{
    name: 'newton',
    lname: 'king',
    link: '123'
  }, {
    name: 'tom',
    lname: 'kurtz',
    link: '123'
  }, {
    name: 'newton',
    lname: 'king',
    link: '456'
  }, {
    name: 'jan',
    lname: 'heckal',
    link: '123'
  }]

for (i = 0, n = arr.length; i < n; i++) {
    var item = arr[i];
    arrResult[ item.name + " - " + item.lname ] = item; // create associative array
}

var i = 0;
var nonDuplicatedArray = [];    
for(var item in arrResult) {
    nonDuplicatedArray[i++] = arrResult[item]; // copy the objects that are now unique
}
console.log(nonDuplicatedArray)
&#13;
&#13;
&#13;