ozansozuoz
ozansozuoz

Reputation: 237

Find missing id between an array of objects and an array of id

I have an array of objects:

const users = [

{
 name:John,
 id:1
},
{
 name:Dude,
 id:2
}
]

And an array of ids:

const ID = [1,2,5]

I would like to to know that 5 is the missing ID so I can fetch that ID.

I have tried nesting for loops

  users.forEach((user, index) => {
    let userExists = false;
    ID.forEach((id) => {
      if (user.id == id) {
        userExists = true;
        return;
      }
    });
    if (!userExists) {
      console.log('user doesnt exists');
    }
  });

There might be a simple solution but currently I can't wrap my head around it

Thanks!

Upvotes: 0

Views: 747

Answers (2)

lejlun
lejlun

Reputation: 4419

Modifying ID in place, using Array#forEach to iterate through each user and Array#splice to remove an item from ID.

const users = [ { name: 'John', id: 1 }, { name: 'Dude', id: 2 }, ];
const ID = [1, 2, 5];

users.forEach(({ id }) => ID.splice(ID.indexOf(id), 1));

console.log(ID);

Upvotes: 1

Alen.Toma
Alen.Toma

Reputation: 4870

Its very easy to do that, use filter()

const users = [
{
 name:"John",
 id:1
},
{
 name:"Dude",
 id:2
}
]

const ID = [1,2,5]

console.log(ID.filter(x=> !users.find(f=> f.id == x)));

Upvotes: 2

Related Questions