skip to Main Content

I’m trying add users to a group and I’m getting current members of created group in order to compare it to all the users in my user list so I can get the users that does not exist in that group. I’m calling users list and group members list from server and both incoming data are arrays.

 for (let i = 0; i < group.members.length; i++) {
    const filteredList = userList?.filter(m => m.id !== group.members.at(i).id)
    console.log(filteredList);
}

This is not working well because I’m getting one or two existing users.

2

Answers


  1. It seems like the issue lies in your comparison logic within the filter function. Your current logic filters out users whose IDs do not match the ID of the current group member being compared. However, this will exclude users who are not exactly the same as the current group member, even if they are in the group.

    Instead, you should check if the current group member exists in the user list,

    const filteredList = userList.filter(user => !group.members.some(member => member.id === user.id));
    console.log(filteredList);
    
    
    Login or Signup to reply.
  2. Change your comparison logic to filter out the user list from m => m.id !== group.members.at(i).id to
    !groupMemberIds?.has(user.id) like below.

    Refer the below code for sample implementation:

    const userList = [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' },
      { id: 3, name: 'Charlie' },
      { id: 4, name: 'David' }
    ];
    
    const group = {
      id: 101,
      name: 'Group A',
      members: [
        { id: 2, name: 'Bob' },
        { id: 4, name: 'David' }
      ]
    };
    
    const groupMemberIds = new Set(group.members.map(member => member.id));
    const nonMembers = userList.filter(user => !groupMemberIds.has(user.id)); // get user list which are not in the group
    console.log(JSON.stringify(nonMembers));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search