P粉4208682942023-09-04 11:51:50
對於更多的資料項目和更多的id
,我會選擇一種建立Set
通過##mapping 每個###itemList項目的
id
...
直接從const idLookup = new Set(itemList.map(({ id }) => id));
或Map
實例比例如更快透過
一次又一次迭代數組尋找或
包含外部
過濾任務。
過濾不匹配的 item-
列表就像...一樣簡單
...範例程式碼...const listOfNonMatchingIds = idList.filter(id => !idLookup.has(id));
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; }
P粉1300978982023-09-04 00:29:22
您可以使用.map()
,然後使用.filter()
和.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]