首页 > 解决方案 > 在两个数组之间迭代以查找匹配值的最有效方法是什么?

问题描述

我需要通过匹配 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);

密码箱

标签: javascriptarraysalgorithmloopsforeach

解决方案


您可以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);


推荐阅读