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

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

当前回答

简单高效的解决方案,运行时间比现有的70多个答案更好:

const ids = array.map(o => o.id)
const filtered = array.filter(({id}, index) => !ids.includes(id, index + 1))

例子:

const arr=[{id:1,名称:“one”},{id:2,名称:‘two’},{id:1,姓名:‘one’}]常量id=arr.map(o=>o.id)constfiltered=arr.filter(({id},索引)=>!ids.includes(id,索引+1))console.log(已过滤)

工作原理:

Array.filter()通过检查先前映射的id数组是否包含当前id来删除所有重复的对象({id}仅将对象销毁为其id)。为了只过滤出实际的重复项,它使用了Array.includes()的第二个参数fromIndex,索引为+1,这将忽略当前对象和所有先前对象。

由于过滤器回调方法的每一次迭代都将只搜索从当前索引+1开始的数组,这也大大减少了运行时间,因为只有以前未过滤的对象才会被检查。

这显然也适用于任何其他不称为id的键、多个键甚至所有键。

其他回答

如果您可以使用诸如下划线或lodash之类的Javascript库,我建议查看它们库中的_.uniq函数。来自lodash:

_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])

基本上,您传入数组,这里是一个对象文本,然后传入要在原始数据数组中删除重复项的属性,如下所示:

var data = [{'name': 'Amir', 'surname': 'Rahnama'}, {'name': 'Amir', 'surname': 'Stevens'}];
var non_duplidated_data = _.uniq(data, 'name'); 

更新:Lodash现在也引入了.uniqBy。

在一行中使用ES6+,您可以按键获得唯一的对象列表:

const key = 'place';
const unique = [...new Map(arr.map(item => [item[key], item])).values()]

可以将其放入函数中:

function getUniqueListBy(arr, key) {
    return [...new Map(arr.map(item => [item[key], item])).values()]
}

下面是一个工作示例:

常量arr=[{地点:“这里”,名称:“x”,其他:“其他stuff1”},{地点:“那里”,名称:“x”,其他:“其他stuff2”},{地点:“这里”,名称:“y”,其他:“其他stuff4”},{地点:“这里”,名称:“z”,其他:“其他stuff5”}]函数getUniqueListBy(arr,key){return[…new Map(arr.Map(item=>[item[key],item])).values()]}const arr1=getUniqueListBy(arr,'place')console.log(“按位置唯一”)console.log(JSON.stringify(arr1))console.log(“\n名称唯一”)const arr2=getUniqueListBy(arr,'name')console.log(JSON.stringify(arr2))

它是如何工作的

首先,以可以用作Map输入的方式重新映射数组。

arr.map(项=>[项[键],项]);

这意味着阵列的每个项目将被转换为具有2个元素的另一个阵列;选定的键作为第一个元素,整个初始项作为第二个元素,这称为条目(例如数组条目、映射条目)。这是一个官方文档,其中有一个示例显示了如何在Map构造函数中添加数组项。

放置钥匙时的示例:

[["here", {place: "here",  name: "x", other: "other stuff1" }], ...]

其次,我们将这个修改后的数组传递给Map构造函数,这就是神奇的发生。映射将消除重复的关键字值,只保留同一关键字的最后插入值。注意:贴图保持插入顺序。(检查贴图和对象之间的差异)

新映射(上面刚刚映射的条目数组)

第三,我们使用map值来检索原始项,但这次没有重复项。

新映射(mappedArr).values()

最后一个是将这些值添加到一个新的数组中,这样它可以看起来像初始结构,并返回:

return[…new Map(mappedArr).values()]

此解决方案适用于任何类型的对象,并检查数组中的每个对象(键、值)。使用临时对象作为哈希表,以查看整个object是否作为键存在。如果找到了Object的字符串表示形式,则该项将从数组中删除。

var arrOfDup=[{'id':123,'name':'name','desc':'some desc'},{“id”:125,“name”:“other name”,“desc”:“Other desc”},{“id”:123,“name”:“name”,“desc”:“some desc”},{“id”:125,“name”:“other name”,“desc”:“Other desc”},{“id”:125,“name”:“other name”,“desc”:“Other desc”}];函数removeDupes(dupArray){让temp={};let tempArray=JSON.parse(JSON.stringify(dupArray));dupArray.forEach((项,位置)=>{if(temp[JSON.stringify(item)]){tempArray.pop();}其他{temp[JSON.stringify(item)]=项;}});返回tempArray;}arrOfDup=removeDupes(arrOfDup);arrOfDup.forEach((项目,位置)=>{console.log(`${pos}位置的数组中的项是${JSON.stringify(项)}`);});

如果您发现需要经常基于特定字段从数组中删除重复的对象,那么创建一个可以从项目中任何位置导入的独特(数组、谓词)函数可能是值得的。这看起来像

const things = [{place:"here",name:"stuff"}, ...];
const distinctThings = distinct(things, thing => thing.place);

不同的函数可以使用上面许多好答案中给出的任何实现。最简单的方法是使用findIndex:

const distinct = (items, predicate) => items.filter((uniqueItem, index) =>
    items.findIndex(item =>
        predicate(item) === predicate(uniqueItem)) === index);

TypeScript函数将数组过滤到其唯一元素,其中唯一性由给定的谓词函数决定:

function uniqueByPredicate<T>(arr: T[], predicate: (a: T, b: T) => boolean): T[] {
  return arr.filter((v1, i, a) => a.findIndex(v2 => predicate(v1, v2)) === i);
}

不打字员:

function uniqueByPredicate(arr, predicate) {
  return l.filter((v1, i, a) => a.findIndex(v2 => predicate(v1, v2)) === i);
}