-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'}
]
noclist
  • 1,659
  • 2
  • 25
  • 66
  • `filter()` and `includes()` ? Please show us your attempt.... – 0stone0 Jul 24 '23 at 15:01
  • Also, it's not 'which items in this object' but 'which objects in this array'. – 0stone0 Jul 24 '23 at 15:03
  • I don't have any attempts because I don't know how to do it. Thanks though. – noclist Jul 24 '23 at 15:05
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – 0stone0 Jul 24 '23 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"_](https://stackoverflow.com/questions/76738740/determine-the-difference-between-values-in-object-and-array) .., especially since the OP already did accept an answer there – Peter Seliger Jul 25 '23 at 08:43

2 Answers2

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]);
piyush s
  • 19
  • 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);
0stone0
  • 34,288
  • 4
  • 39
  • 64