首页 > 解决方案 > 给定两个数组,在数组 A 中找到数组 B 中具有唯一值的项

问题描述

我有两个数组,其中一个太大了。而另一个的最大长度是 9。我试图实现的是,我想通过给出小数组的项目来找到更大的数组中的项目。

我做了类似的事情;

const largeArray = [
  { id: 23 },
  { id: 12 },
  { id: 43 },
  { id: 54 },
  { id: 15 },
  //and so on and all ids are unique
]

const smallArray = [23, 12, 43]


smallArray.map(smallArrayItem => {
  largeArray.map(largeArrayItem => {
    if (smallArrayItem === largeArrayItem.id) {
      console.log(largeArrayItem)
    }
  })
})

但 IMO 这不是一种有效的方法。它很慢。查找项目大约需要 2 秒。如何以适当的方式加快搜索速度?

标签: javascriptarraysperformanceiteration

解决方案


请使用过滤器并包含

const largeArray = [
  { id: 23 },
  { id: 12 },
  { id: 43 },
  { id: 54 },
  { id: 15 },
]

const smallArray = [23, 12, 43]

const diff = largeArray.filter(item => !smallArray.includes(item.id));

console.log(diff);


推荐阅读