如何删除对象数组中出现多次的任何对象? [英] How to remove any objects that appear more than once in an array of objects?
本文介绍了如何删除对象数组中出现多次的任何对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个像这样的数组:
[{编号:1标题:'foo'},{编号:2标题栏'},{id:3,标题:蝙蝠"},{编号:4标题:"bantz"},{编号:2标题栏'},{id:3,标题:蝙蝠"}]
我想返回一个数组,其中包含仅出现一次的所有对象.因此,对于此示例,所需的输出将是:
[{编号:1标题:'foo'},{编号:4标题:"bantz"}]
我尝试了几种使用 reduce()
和 indexOf()
来解决此问题的方法,例如解决方案
您可以使用 Map
来避免不得不一次又一次地浏览数组,这将导致效率低下的 O(n²)时间复杂度.这是 O(n):
function getUniquesOnly(data){返回Array.from(data.reduce((acc,o)=> acc.set(o.id,acc.has(o.id)?0:o),新Map),(([[k,v])=> v)).filter(x => x);}var数据= [{编号:1标题:'foo'},{编号:2标题栏'},{id:3,标题:蝙蝠"},{编号:4标题:"bantz"},{编号:2标题栏'},{id:3,标题:蝙蝠"}];console.log(getUniquesOnly(data));
If I have an array like:
[
{
id: 1,
title: 'foo'
},
{
id: 2,
title: 'bar'
},
{
id: 3,
title: 'bat'
},
{
id: 4,
title: 'bantz'
},
{
id: 2,
title: 'bar'
},
{
id: 3,
title: 'bat'
}
]
And I want to return an array that contains any objects that appear only once. So for this example, the desired output would be:
[
{
id: 1,
title: 'foo'
},
{
id: 4,
title: 'bantz'
}
]
I have tried a few different approaches that I have found to solve this using reduce()
and indexOf()
, like this solution, but they do not work with objects for some reason.
Any assistance would be greatly appreciated.
解决方案
You could use a Map
to avoid having to look through the array again and again, which would lead to inefficient O(n²) time-complexity. This is O(n):
function getUniquesOnly(data) {
return Array.from(
data.reduce( (acc, o) => acc.set(o.id, acc.has(o.id) ? 0 : o), new Map),
(([k,v]) => v)
).filter( x => x );
}
var data = [
{
id: 1,
title: 'foo'
},
{
id: 2,
title: 'bar'
},
{
id: 3,
title: 'bat'
},
{
id: 4,
title: 'bantz'
},
{
id: 2,
title: 'bar'
},
{
id: 3,
title: 'bat'
}
];
console.log(getUniquesOnly(data));
这篇关于如何删除对象数组中出现多次的任何对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文