-2

Given the following array

[60, 1456]

How can I determine which items in this object do not have a corresponding id to the numbers in the array?

[
  {id: 60, itemName: 'Main Location - Cleveland'},
  {id: 1453, itemName: 'Second Location - Cleveland'},
  {id: 1456, itemName: 'Third Location - New York'}
]
5
  • filter() and includes() ? Please show us your attempt.... Commented Jul 24, 2023 at 15:01
  • Also, it's not 'which items in this object' but 'which objects in this array'. Commented Jul 24, 2023 at 15:03
  • I don't have any attempts because I don't know how to do it. Thanks though. Commented Jul 24, 2023 at 15:05
  • Does this answer your question? How do I check if an array includes a value in JavaScript? Commented Jul 24, 2023 at 15:06
  • Why does the OP ask almost the same question on exactly the same subject as already 3 days before ... "Determine the difference between values in object and array" .., especially since the OP already did accept an answer there Commented Jul 25, 2023 at 8:43

2 Answers 2

1

Use filter() combined with includes() to check if the id does not (!) exists in the ids array:

const ids = [60, 1456];
const data = [
  {id: 60, itemName: 'Main Location - Cleveland'},
  {id: 1453, itemName: 'Second Location - Cleveland'},
  {id: 1456, itemName: 'Third Location - New York'}
];

const res = data.filter(({ id }) => !ids.includes(id));
console.log(res);

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

Comments

1
You can try combination of filter & includes or filter & find or filter indexOf

const a = [60, 1456];

const b = [
  {id: 60, itemName: 'Main Location - Cleveland'},
  {id: 1453, itemName: 'Second Location - Cleveland'},
  {id: 1456, itemName: 'Third Location - New York'}
];

const idExists = b.filter(ob => {
 // const includes = !a.includes(ob.id);
 const find = a.find(id => id !== ob.id);

  return find;
})

// Efficient approach

const mapOfIds = a.reduce(acc, id => {...acc, [id]: id}, {});
const idExists = b.filter(ob => !mapOfIds[ob.id]);

3 Comments

Why is this upvoted? Calling find for each item in the array is incredibly inefficient....
With includes also we are internally iterating on array for each item & with indexOf as well
Added efficient approach as well

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.