javascript - 在两个数组之间迭代以查找匹配值的最有效方法是什么?
问题描述
我需要通过匹配 id 数组来查找数组中的对象。id 数组可以更长或等于人员数组的长度。我使用 forEach 循环的 people 数组并在内部使用了 include 方法来查找匹配的 id,但不确定它是否是好方法。有没有办法优化搜索算法?
const ids = [1, 4, 9, 7, 5, 3];
const matchedPersons = [];
const persons = [
{
id: 1,
name: "James"
},
{
id: 2,
name: "Alan"
},
{
id: 3,
name: "Marry"
}
];
persons.forEach((person) => {
if (ids.includes(person.id)) {
matchedPersons.push(person);
}
});
console.log(matchedPersons);
解决方案
您可以Set
使用 O(1) 进行检查。
const
ids = [1, 4, 9, 7, 5, 3],
persons = [{ id: 1, name: "James" }, { id: 2, name: "Alan" }, { id: 3, name: "Marry" }],
idsSet = new Set(ids),
matchedPersons = persons.filter(({ id }) => idsSet.has(id));
console.log(matchedPersons);
推荐阅读
- azure - AZURE HD INSIGHT (Cluster) 将 CSV 文件导入存储:创建表
- go - 使用 godoc 启动本地文档服务器时出现问题
- excel - Excel Power Query:从具有多个未固定工作表的多个未固定文件中获取数据
- python - 计算自上次维护以来的日期差异的有效方法是什么?
- python - 使用 Boto3 从 DynamoDB 获取时出错
- django - 带有验证的 Django 文件上传不起作用
- python - 如何使 send() 函数接受字节字符串作为连续更新的输入?
- python - openpyxl load_workbook 错误:对非序列类型的迭代
- php - PHP分页在本地版本上工作正常,但在服务器上不工作
- java - 构造函数没有初始化正确的值