【问题标题】:What is the most efficient way to iterate between two arrays to find matched values?在两个数组之间迭代以查找匹配值的最有效方法是什么?
【发布时间】:2021-07-30 00:14:43
【问题描述】:

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

codesanbox

【问题讨论】:

  • 现在需要多长时间?它需要多快?阵列通常有多大?它是按 id 排序的数组之一?
  • 现在需要多长时间?它需要多快? - 目前很难回答,因为没有要测试的数据。阵列通常有多大? - 两个数组都可以存储多达 100 万个值

标签: javascript arrays algorithm loops foreach


【解决方案1】:

您可以使用地图https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get

    const ids = [1, 4, 9, 7, 5, 3];
    const matchedPersons = [];
    const persons = [
    {
        id: 1,
        name: "James"
    },
    {
        id: 2,
        name: "Alan"
    },
    {
        id: 3,
        name: "Marry"
    }
    ];

    const personsMap = new Map()
    persons.forEach((person) => {
        personsMap.set(person.id, person)    
    });

    persons.forEach((person) => {
    if (personsMap.has(person.id)) {
        matchedPersons.push(personsMap.get(person.id));
    }
    });

    console.log(matchedPersons);

【讨论】:

    【解决方案2】:

    你最好使用filter。它完全按照它的意图去做:

    const ids = [1, 4, 9, 7, 5, 3];
    const persons = [
      {
        id: 1,
        name: "James"
      },
      {
        id: 2,
        name: "Alan"
      },
      {
        id: 3,
        name: "Marry"
      }
    ];
    
    const matchedPersons = persons.filter(({id}) => ids.includes(id))
    console.log(matchedPersons)

    【讨论】:

      【解决方案3】:

      您可以使用 O(1) 的 Set 进行检查。

      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);

      【讨论】:

      • matchedPersons = person.filter(({ id }) => idsSet.has(id)); => 这个 O(1) 怎么样?搜索本身是 O(1),但基于 n 迭代必须发生。
      • n 用于过滤器。
      • 所以我想我们在这点上是一样的,只是确认一下。我正在确保我没有遗漏任何东西。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多