Home > Blockchain >  I'm trying to make an array with only values ​that are not contained in the other array (non-re
I'm trying to make an array with only values ​that are not contained in the other array (non-re

Time:12-20

I have an array of available users that can be invited and also another array with all joined users to the particular chat. I need to check which of the available users have joined the chat and should be listed elsewhere.

Finally, I want to get an array with only the available users who have not joined the chat.

let availablеUsers = [{id:1,name:'Dani'}, {id:2,name:'Ani'}, {id:3,name:'Marta'}] 
let allUsers = [{id:2,name:'Ani'},{id:10,name:'John'}, {id:3,name:'Marta'}] 

The first thing I try to do is find those who are already participating in the chat:

 let joinedUsers = availablеUsers.map((user) => {
    return allUsers?.find((u) => u.id === user.id);
  });

And i get this : [undefined, {… Аni}, {… Marta}]

Then I try to filter the array of available users so that I remove from it those that are in the newly created array and here's the problem I don't know how to do this :/

My idea is something like that:

availablеUsers = availablеUsers.filter((user) => {
    //HERE I don't know what logic to write 
    return joinedUsers?.map((m) => m?.id !== user.id); // this doesn't work, just an example
  });

My goal is to have only those users not contained in the other remain in the availableUsers array.

In the example I have given at the end in the array should remain only {id:1,name:'Dani'}

I welcome any suggestions. If it can do it with chaining, without the extra variable for joinedUsers it would be even better!

CodePudding user response:

There's no need for joinedUsers. Just use find() or some() in the filter() callback, and invert the test.

availableUsers = availableUsers.filter(user => !allUsers.some(u => u.id == user.id))

CodePudding user response:

if users are uniquely identified by id you can use just a filter with a Set of known users:

let availablеUsers = [{id:1,name:'Dani'}, {id:2,name:'Ani'}, {id:3,name:'Marta'}] 
let allUsers = [{id:2,name:'Ani'},{id:10,name:'John'}, {id:3,name:'Marta'}]

let joinedUsers = availablеUsers.filter(
  function ({id}) {
    return this.has(id);
  },
  new Set(allUsers.map(({id}) => id))
);

Accordingly, you can use the same to update availablеUsers in one go:

availablеUsers = availablеUsers.filter(
  function ({id}) {
    return !this.has(id);
  },
  new Set(allUsers.map(({id}) => id))
);

it's not super clear why or when you need !== vs === but the concept is: use a set and use filter instead of map when you want to filter a Set works harder while constructed but it's blazing fast while used via has()

  • Related