skip to Main Content

I have the following object and array of numbers. How can I tell which number in the array does not exist as an id in the object? In the following example, I would want 1453.

[
  {id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland'}
  {id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York'}
]

[60, 1453, 1456]

3

Answers


  1. You could create an IDs list of the existing data IDs using .map(), and then use .filter() and .includes()

    const data = [
      {id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland'},
      {id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York'}
    ]
    
    const ids = [60, 1453, 1456];
    const dataIDs = data.map(ob => ob.id);  // [60, 1456]
    const notExistentIDs = ids.filter(id => !dataIDs.includes(id));
    
    console.log(notExistentIDs);  // [1453]

    which will return an Array of all the Object IDs (from data) not listed in your reference ids Array.

    Login or Signup to reply.
  2. @Roko’s solution is absolutely correct and probably a lot faster. Here’s my alternative approach using .reduce() and .some():

    const data = [
      { id: 60, itemName: "Main Location - 1100 Superior Road - Cleveland" },
      { id: 1456, itemName: "Third Location - 107,West 20th Street,Manhattan - New York" }
    ];
    const ids = [60, 1453, 1456];
    
    const result = ids.reduce(
      (acc, curr) =>
      data.some(d => d.id === curr) ? acc : [...acc, curr], []
    );
    
    console.log(result);
    Login or Signup to reply.
  3. For a grater amount of data-items and a grater amount of ids I would choose an approach which creates a Set based lookup via mapping each of an itemList item’s id

    const idLookup = new Set(itemList.map(({ id }) => id));
    

    Looking up items directly from a Set or a Map instance is much faster than e.g. iterating again and again an array via find or includes for each iteration step of an outer filter task.

    Filtering a list of non matching item-ids then is as straightforward as …

    const listOfNonMatchingIds = idList.filter(id => !idLookup.has(id));
    

    … example code …

    const itemList = [
      { id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland' },
      { id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York' },
    ];
    const idList = [60, 1453, 1456];
    
    const idLookup = new Set(itemList.map(({ id }) => id));
    const listOfNonMatchingIds = idList.filter(id => !idLookup.has(id));
    
    console.log({ listOfNonMatchingIds });
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search