0

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))
3
  • Now after your edit, your code would work too. Commented Jun 7, 2018 at 14:29
  • @baao I just got it after writing the post. As There is a answer postet I can't delete the post. Commented Jun 7, 2018 at 14:30
  • Do you want to accept my answer or do you want me to delete my answer? You should really use some though. Commented Jun 7, 2018 at 14:31

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.