Reputation: 17332
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
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
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
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