我有一个包含对象数组的对象。
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"}
您还可以创建一个通用函数,该函数将根据传递给该函数的对象键过滤数组
function getUnique(arr, comp) {
return arr
.map(e => e[comp])
.map((e, i, final) => final.indexOf(e) === i && i) // store the keys of the unique objects
.filter(e => arr[e]).map(e => arr[e]); // eliminate the dead keys & store unique objects
}
你可以这样调用函数,
getUnique(things.thing,'name') // to filter on basis of name
getUnique(things.thing,'place') // to filter on basis of place
简单高效的解决方案,运行时间比现有的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的键、多个键甚至所有键。
向列表中再添加一个。将ES6和Array.reduce与Array.find一起使用。在此示例中,根据guid属性筛选对象。
let filtered = array.reduce((accumulator, current) => {
if (! accumulator.find(({guid}) => guid === current.guid)) {
accumulator.push(current);
}
return accumulator;
}, []);
扩展此选项以允许选择属性并将其压缩为一行:
const uniqify = (array, key) => array.reduce((prev, curr) => prev.find(a => a[key] === curr[key]) ? prev : prev.push(curr) && prev, []);
要使用它,请将对象数组和要进行重复数据消除的键的名称作为字符串值传递:
const result = uniqify(myArrayOfObjects, 'guid')