typescript - 遍历 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;
}
});
}
解决方案
一种解决方案是保留一组您根本看过的数字,以及另一组您只看过一次的数字,如果您以前看过第二组数字,请从第二组中删除它:
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]));
请注意,我已经让它返回一个数组,因为从我的第二个示例中可以看出,数组中可能有多个唯一值。
推荐阅读
- algorithm - 在螺旋中找到特定元素坐标的算法
- javascript - 如何在 Angular 中实现磁性滚动?
- reactjs - 样式化组件的 Nth-child 不起作用
- github - Travis CI - 401 - 构建失败 - 私人回购上的错误凭证
- r - 因子 `country` 包含隐式 NA,考虑使用 `forcats::fct_explicit_na`
- jquery - 打开将“溢出:隐藏”分配给正文的模式或窗口时,页面滚动到最顶部
- azureservicebus - 是否可以从观察者使用 azure 服务总线发送消息?
- javascript - 如何将 $lookup 的结果与子文档合并
- jquery - 谷歌地图自动完成到ajax注入
- mongodb - 意外关机mongos版v4.2.0