search

Home  >  Q&A  >  body text

Determine the difference between values ​​in an object and an array

<p>I have the following array of objects and numbers. How to tell which number in the array does not exist as an id in the object? In the example below, I want 1453. </p> <pre class="brush:php;toolbar:false;">[ {id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland'} {id: 1456, itemName: 'Third Location - 107,West 20th Street,Manhattan - New York'} ] [60, 1453, 1456]</pre></p>
P粉930534280P粉930534280455 days ago544

reply all(2)I'll reply

  • P粉420868294

    P粉4208682942023-09-04 11:51:50

    For more data items and more id, I would choose one to create Set via mapping the id... of each itemList

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

    Directly from a Collection or Map instance is faster than e.g. by iterating over the array over and over again or contains external filtering tasks.

    Filtering unmatched item-id List is as simple 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; }

    reply
    0
  • P粉130097898

    P粉1300978982023-09-04 00:29:22

    You can use .map() and then .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]

    reply
    0
  • Cancelreply