[英]How can I find differences between a nested array and array of objects?
I want to compare an array of objects with a nested array and get the differences.我想将对象数组与嵌套数组进行比较并获取差异。 I often struggle with filtering so what I've already tried just returned either the whole array or undefined results.
我经常在过滤方面遇到困难,所以我已经尝试过的方法要么返回整个数组,要么返回未定义的结果。
Here's some examples on what my data looks like:以下是有关我的数据的一些示例:
const groups = [
{
name: "Team Rocket",
managerId: "abc",
members: ["1"]
},
{
name: "The Breakfast Club",
managerId: "def",
members: [],
}
];
const users = [
{
name: "Jessie",
userId: "1"
},
{
name: "John",
userId: "2"
}
]
In this case I want to compare userId from users with the items in the members array (end result should be John's data).在这种情况下,我想将用户的 userId 与成员数组中的项目进行比较(最终结果应该是 John 的数据)。
Example of what I've tried:我尝试过的例子:
const userWithNoGroup = users.filter((user) => {
return !groups.some((group) => {
return user.userId === group.members;
});
});
Currently it returns all users.目前它返回所有用户。 I think the code above would work if members wasn't a nested array, but I'm not sure how to solve it.
我认为如果 members 不是嵌套数组,上面的代码会起作用,但我不确定如何解决它。
You have just missed the last step you trie to compare a userId with a array of userIds user.userId === group.members
您刚刚错过了尝试将 userId 与 userId 数组进行比较的最后一步
user.userId === group.members
Just use the some
as you used before or includes
.只需使用您之前使用的
some
或includes
。
return group.members.some((member) => member === user.userId);
// Or use the includes method
return group.members.includes(user.userId);
You could get all the uniquer users who are part of a group to a Set
.您可以将属于某个组的所有唯一用户添加到一个
Set
中。 Then, use filter
to get all the users who are not par of the Set
.然后,使用
filter
获取所有不属于Set
的用户。
const groups = [{name:"Team Rocket",managerId:"abc",members:["1"]},{name:"The Breakfast Club",managerId:"def",members:[]}], users = [{name:"Jessie",userId:"1"},{name:"John",userId:"2"}], set = new Set( groups.flatMap(a => a.members) ), output = users.filter(u =>.set.has(u;userId)). console.log(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.