user3142695
user3142695

Reputation: 17332

Check if every id has an existing object in array

I would like to check if there is an existing object for every id of an array.

const ids = [ 'xxnQt5X8pfbcJMn6i', 'fbcJMn6ixxnQt5X8p' ]
const target = [
  { _id: 'xxnQt5X8pfbcJMn6i' },
  { _id: 'Qt5X8pfbcJMn6ixxn' },
]

In this example I would like to get false, as the second ID (fbcJMn6ixxnQt5X8p) is not existing.

This should return true:

const ids = [ 'xxnQt5X8pfbcJMn6i', 'fbcJMn6ixxnQt5X8p' ]
const target = [
  { _id: 'xxnQt5X8pfbcJMn6i' },
  { _id: 'Qt5X8pfbcJMn6ixxn' },
  { _id: 'fbcJMn6ixxnQt5X8p' },
]

This is what I've tried:

ids.every(id => target.find(element => element._id === id))

Upvotes: 0

Views: 58

Answers (3)

Emanuele
Emanuele

Reputation: 814

Since every is itself a checker method it's return true or false through the provided function. So you can simply return false:

const res = const res = ids.every(id => target._id === id); console.log(res);

or true:

const res = ids.every(id => target._id !== id); console.log(res);

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138247

With a lot of entries, it might be faster to use a Set (so we get O(n + m) instead of O(n * m)) :

const idSet = new Set(target.map(el => el._id));
const result = ids.every(id => idSet.has(id));

Upvotes: 1

baao
baao

Reputation: 73221

You're pretty close, you need to pass a function instead of an object to find though - and I'd recommend to use some() instead of find if you only want to know about if it exists, rather than you need the object in return.

const ids = [ 'xxnQt5X8pfbcJMn6i', 'fbcJMn6ixxnQt5X8p' ]
const target = [
  { _id: 'xxnQt5X8pfbcJMn6i' },
  { _id: 'Qt5X8pfbcJMn6ixxn' },
  { _id: 'fbcJMn6ixxnQt5X8p' },
]

const allIn = ids.every(id => target.some(({_id}) => id === _id));
console.log(allIn);

Upvotes: 1

Related Questions