skip to Main Content

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'}
]

2

Answers


  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]);
    
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search