Home > OS >  Check if all the users in an array have at least one element with an ID equal to an array of IDs?
Check if all the users in an array have at least one element with an ID equal to an array of IDs?

Time:11-30

The title is very hard to read, I get it.

I have an array of objects with my users inside of it.

const users = [{
  id: 0,
  name: "Test user 01",
}, {
  id: 1,
  name: "Test user 02"
}, {
  id: 3,
  name: "Test user 03"
}]

const idsToCheck = [2, 4]; 

I want a boolean True if at least one element of users have an ID equal to 2 OR to 4.

I wanted to use Array.some but, with an array to check and not a single value, I cannot loop inside of the method without a lint error.

Thanks

CodePudding user response:

Does this looks OK to you?

const users = [{
  id: 0,
  name: "Test user 01",
}, {
  id: 1,
  name: "Test user 02"
}, {
  id: 3,
  name: "Test user 03"
}]

const idsToCheck = [2, 4];

const isPresent = users.some(user => idsToCheck.some(id => id === user.id));

console.log(isPresent)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Some does work.

We are testing numeric IDs against an array of ints - there is reference equality between the IDs and the array elements so the includes is the shortest method over a double some

const users = [{
  id: 0,
  name: "Test user 01",
}, {
  id: 1,
  name: "Test user 02"
}, {
  id: 3,
  name: "Test user 03"
}]

const idsToCheck = [2, 4];

const bool = users.some(({id}) => idsToCheck.includes(id))
console.log(bool)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related