Home > front end >  How can I find differences between a nested array and array of objects?
How can I find differences between a nested array and array of objects?

Time:12-08

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).

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.

CodePudding user response:

You have just missed the last step you trie to compare a userId with a array of userIds user.userId === group.members

Just use the some as you used before or includes.

    return group.members.some((member) => member === user.userId);
    // Or use the includes method
    return group.members.includes(user.userId);

CodePudding user response:

You could get all the uniquer users who are part of a group to a Set. Then, use filter to get all the users who are not par of the 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)

  • Related