javascript - 给定两个数组,在数组 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 秒。如何以适当的方式加快搜索速度?
解决方案
请使用过滤器并包含
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);
推荐阅读
- php - 当网格的一侧开始比另一侧增加更多时,如何修复自动添加到css网格元素的填充
- python - 207 类(许多与一个对象),电影
- swift - 将主题/发布者转换为另一个发布者
- python - Ping 命令在 Discord.py 机器人中不起作用
- laravel - 无法登录到 laravel 项目
- amazon-web-services - 如何使用域加入和预安装的应用程序创建 Windows ec2 实例
- javascript - 如何访问“msg.guild.members.fetch()”中的值
- html - 在 div 标签中居中图像
- javascript - 如何使用'=>'将日期字符串连接到另一个字符串
- android-studio - 设备选择在 Android Studio 4.0.1 中显示 Loading...