ES6-从对象数组中删除重复项 [英] ES6 - Removing duplicates from array of objects
本文介绍了ES6-从对象数组中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设对象数组如下:
const listOfTags = [
{id: 1, label: "Hello", color: "red", sorting: 0},
{id: 2, label: "World", color: "green", sorting: 1},
{id: 3, label: "Hello", color: "blue", sorting: 4},
{id: 4, label: "Sunshine", color: "yellow", sorting: 5},
{id: 5, label: "Hello", color: "red", sorting: 6},
]
如果标签和颜色相同,则将重复输入.在这种情况下,id = 1和id = 5的对象是重复项.
A duplicate entry would be if label and color are the same. In this case Objects with id = 1 and id = 5 are duplicates.
如何过滤此数组并删除重复项?
How can I filter this array and remove duplicates?
我知道解决方案,您可以在其中使用类似以下内容的一个键进行过滤:
I know solutions where you can filter against one key with something like:
const unique = [... new Set(listOfTags.map(tag => tag.label)]
那多个键呢?
根据评论中的请求,此处为所需结果:
As per request in comment, here the desired result:
[
{id: 1, label: "Hello", color: "red", sorting: 0},
{id: 2, label: "World", color: "green", sorting: 1},
{id: 3, label: "Hello", color: "blue", sorting: 4},
{id: 4, label: "Sunshine", color: "yellow", sorting: 5},
]
推荐答案
您可以在闭包中使用Set
进行过滤.
You could use a Set
in a closure for filtering.
const
listOfTags = [{ id: 1, label: "Hello", color: "red", sorting: 0 }, { id: 2, label: "World", color: "green", sorting: 1 }, { id: 3, label: "Hello", color: "blue", sorting: 4 }, { id: 4, label: "Sunshine", color: "yellow", sorting: 5 }, { id: 5, label: "Hello", color: "red", sorting: 6 }],
keys = ['label', 'color'],
filtered = listOfTags.filter(
(s => o =>
(k => !s.has(k) && s.add(k))
(keys.map(k => o[k]).join('|'))
)
(new Set)
);
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于ES6-从对象数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文