首页 > 解决方案 > 遍历 TypeScript 中的 Object 以查找特定值

问题描述

试图在对象中找到映射到值“1”的键。

就目前而言,该函数返回未定义。

这是预期的行为。

input : deliveryIds: [5,4,5,3,3]
output: 4

这是遍历对象以搜索映射到“1”的键的代码。

非常感谢我需要更改的任何帮助。

function findMissingQuad(deliveryIds: number[]) {
  const idsToOccurrences = {};

  deliveryIds.forEach(id => {
    if (idsToOccurrences[id]) {
      idsToOccurrences[id]++;
    } else {
      idsToOccurrences[id] = 1 || [];
    }
  });

  return Object.keys(idsToOccurrences).forEach(id => {
    if (idsToOccurrences[id] === 1) {
      return id;
    }
  });
}

标签: typescriptobject

解决方案


一种解决方案是保留一组您根本看过的数字,以及另一组您只看过一次的数字,如果您以前看过第二组数字,请从第二组中删除它:

function findMissingQuad(deliveryIds/*: number[]*/) {
    const seen = new Set();
    const once = new Set();
    for (const id of deliveryIds) {
        if (seen.has(id)) {
            // We'e seen this one before
            once.delete(id);
        } else {
            // First time we've seen this one
            seen.add(id);
            once.add(id);
        }
    }
    return [...once];
}

console.log(findMissingQuad([5, 4, 5, 3, 3]));
console.log(findMissingQuad([5, 4, 5, 2, 3, 3]));

请注意,我已经让它返回一个数组,因为从我的第二个示例中可以看出,数组中可能有多个唯一值。


推荐阅读