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

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的键、多个键甚至所有键。

其他回答

这个解决方案最适合我,因为它使用了Array.from方法,而且它的长度更短,可读性更强。

let person = [
{name: "john"}, 
{name: "jane"}, 
{name: "imelda"}, 
{name: "john"},
{name: "jane"}
];

const data = Array.from(new Set(person.map(JSON.stringify))).map(JSON.parse);
console.log(data);

如果数组包含对象,则可以使用此方法删除重复的

const persons= [
      { id: 1, name: 'John',phone:'23' },
      { id: 2, name: 'Jane',phone:'23'},
      { id: 1, name: 'Johnny',phone:'56' },
      { id: 4, name: 'Alice',phone:'67' },
    ];
const unique = [...new Map(persons.map((m) => [m.id, m])).values()];

如果删除基于电话的重复项,只需将m.id替换为m.phone

const unique = [...new Map(persons.map((m) => [m.phone, m])).values()];

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

在数组中查找唯一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)

对于一个可读且简单的解决方案搜索者,她是我的版本:

    function removeDupplicationsFromArrayByProp(originalArray, prop) {
        let results = {};
        for(let i=0; i<originalArray.length;i++){
            results[originalArray[i][prop]] = originalArray[i];
        }
        return Object.values(results);
    }

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”});console.log(things);函数removeDucplicate(result,id){让duplicate={};return result.filter(ele=>!duplicate[ele[id]]&&(duplicate[ele[id]]=true));}let resolverrarray=删除重复(things.thing,'place')console.log(resolverrarray);