我有一个包含对象数组的对象。
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 genFilterData(arr, key, key1) {
let data = [];
data = [...new Map(arr.map((x) => [x[key] || x[key1], x])).values()];
const makeData = [];
for (let i = 0; i < data.length; i += 1) {
makeData.push({ [key]: data[i][key], [key1]: data[i][key1] });
}
return makeData;
}
const arr = [
{make: "here1", makeText:'hj',k:9,l:99},
{make: "here", makeText:'hj',k:9,l:9},
{make: "here", makeText:'hj',k:9,l:9}]
const finalData= genFilterData(data, 'Make', 'MakeText');
console.log(finalData);
简单高效的解决方案,运行时间比现有的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的键、多个键甚至所有键。