我有一个包含对象数组的对象。

obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});

我想知道从数组中删除重复对象的最佳方法是什么。例如,obj.arr将变成。。。

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}

当前回答

我们可以利用Javascript的Set对象和Array的Filter函数:例如:

//示例阵列const arr=[{id:“1”},{id:“2”};//收集要过滤元素的唯一元素Id。constuniqIds=arr.reduce((id,el)=>ids.add(el.id),new Set());//过滤出uniq元素。const uniqElements=arr.filter((el)=>uniqIds.delete(el.id));console.log(uniqElements);

其他回答

这里有一个使用JavaScript新过滤功能的解决方案,非常简单。假设你有一个这样的数组。

var duplicatesArray = ['AKASH','AKASH','NAVIN','HARISH','NAVIN','HARISH','AKASH','MANJULIKA','AKASH','TAPASWENI','MANJULIKA','HARISH','TAPASWENI','AKASH','MANISH','HARISH','TAPASWENI','MANJULIKA','MANISH'];

filter函数将允许您为数组中的每个元素使用一次回调函数来创建一个新数组。所以你可以这样设置唯一的数组。

var uniqueArray = duplicatesArray.filter(function(elem, pos) {return duplicatesArray.indexOf(elem) == pos;});

在这种情况下,您的唯一数组将遍历重复数组中的所有值。elem变量表示数组中元素的值(mike、james、james和alex),位置是它在数组中的0索引位置(0,1,2,3…),duplicatesArray.indexOf(elem)值只是该元素在原始数组中第一次出现的索引。因此,因为元素'james'是重复的,所以当我们循环遍历duplicatesArray中的所有元素并将它们推送到uniqueArray时,第一次命中james时,我们的“pos”值为1,indexOf(elem)也为1,因此james被推送到unique Array。第二次命中James时,我们的“pos”值为2,indexOf(elem)仍然为1(因为它只找到数组元素的第一个实例),因此不会推送重复项。因此,uniqueArray只包含唯一值。

这是上述功能的演示。单击此处查看上述功能示例

let data = [
  {
    'name': 'Amir',
    'surname': 'Rahnama'
  }, 
  {
    'name': 'Amir',
    'surname': 'Stevens'
  }
];
let non_duplicated_data = _.uniqBy(data, 'name');

这里是ES6的解决方案,您只想保留最后一项。该解决方案功能强大,符合Airbnb风格。

const things = {
  thing: [
    { place: 'here', name: 'stuff' },
    { place: 'there', name: 'morestuff1' },
    { place: 'there', name: 'morestuff2' }, 
  ],
};

const removeDuplicates = (array, key) => {
  return array.reduce((arr, item) => {
    const removed = arr.filter(i => i[key] !== item[key]);
    return [...removed, item];
  }, []);
};

console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]

带过滤器的内衬(保留订单)

在数组中查找唯一id。

arr.filter((v,i,a)=>a.findIndex(v2=>(v2.id===v.id))===i)

如果顺序不重要,映射解决方案将更快:使用映射解决方案


多个财产独有(地点和名称)

arr.filter((v,i,a)=>a.findIndex(v2=>['place','name'].every(k=>v2[k] ===v[k]))===i)

所有财产都是唯一的(对于大型阵列来说,这将很慢)

arr.filter((v,i,a)=>a.findIndex(v2=>(JSON.stringify(v2) === JSON.stringify(v)))===i)

通过用findLastIndex替换findIndex来保留最后一次出现。

arr.filter((v,i,a)=>a.findLastIndex(v2=>(v2.place === v.place))===i)

这是我的两分钱。如果您知道财产的顺序相同,则可以将元素串接起来,并从数组中删除重复项,然后再次解析数组。类似于:

var things=新对象();things.thing=新数组();thing.thing.push({place:“here”,name:“stuff”});things.thing.push({place:“there”,name:“morestuff”});things.thing.push({place:“there”,name:“morestuff”});let-stringified=things.thing.map(i=>JSON.sringify(i));let unique=stringified.filter((k,idx)=>stringified.indexOf(k)==idx).map(j=>JSON.parse(j))console.log(唯一);