[英]How to get an array without duplicates from object elements
I have an object with groups (as an example).我有一个带有组的 object(例如)。 Each group object contains one
header
id and multiple trigger
ids.每组 object 包含一个
header
id 和多个trigger
id。 I want to get an array of all the triggers of all groups without duplicates.我想获得所有组的所有触发器的数组而没有重复。
An example would be this:一个例子是这样的:
const groups = {
group1: { header: 9, trigger: [10,11] },
group2: { header: 15, trigger: [11, 17] }
}
Currently, I am doing it like so:目前,我这样做是这样的:
const triggers = Array.from(groups, x => x.trigger);
This gives me the following result: [[10,11],[11,17]]
这给了我以下结果:
[[10,11],[11,17]]
My plan is to get something like this: [10,11,17]
.我的计划是得到这样的东西:
[10,11,17]
。 They don't have to be sorted but the duplicates (in this case 11
) has to be removed.不必对它们进行排序,但必须删除重复项(在本例中为
11
)。 Is there any fast way of doing it?有什么快速的方法吗? Otherwise I would loop through this array now and then concat to a new array but I think there is a faster and better solution.
否则我会不时遍历这个数组,然后连接到一个新数组,但我认为有一个更快更好的解决方案。
Here is a one-liner using Set and .flatMap()
method这是使用Set和
.flatMap()
方法的单线
const groups = { group1: { header: 9, trigger: [10,11] }, group2: { header: 15, trigger: [11, 17] } } const triggers = [...new Set(Object.values(groups).flatMap(x=>x.trigger))] console.log(triggers)
Here's a pretty quick way using a Set
这是使用
Set
的一种非常快速的方法
const groups = { group1: { header: 9, trigger: [10,11] }, group2: { header: 15, trigger: [11, 17] } } const addGroupTrigger = (triggersSet, [, group]) => { for (const trigger of group.trigger) { triggersSet.add(trigger) } return triggersSet } console.log( Array.from(Object.entries(groups).reduce(addGroupTrigger, new Set())) )
Using the function Array.from
as in your code, I can't make it work like you said.在你的代码中使用 function
Array.from
,我不能让它像你说的那样工作。
Btw, I have this snippet, take a look to see if it helps:顺便说一句,我有这个片段,看看它是否有帮助:
const groups = {
group1: { header: 9, trigger: [10,11] },
group2: { header: 15, trigger: [11, 17] }
}
var arr = []
Object.keys(groups).forEach(function (key) {
arr = arr.concat(groups[key].trigger);
});
console.log('Array with DUP: ', arr);
var set = new Set(arr);
arr = Array.from(set);
console.log('Array without DUP: ', arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.