You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript优化:如何单次遍历Map按值拆分键至两个字符串数组

优化Map键值分组的实现方法

你可以只遍历一次Map,在遍历过程中把键分别存入对应的数组,这样能避免重复遍历带来的性能损耗,尤其是当Map里的条目数量较多时,这种优化效果会更明显。

方式一:使用for...of循环

const trueKeys: string[] = [];
const falseKeys: string[] = [];

for (const [key, value] of myMap.entries()) {
  if (value) {
    trueKeys.push(key);
  } else {
    falseKeys.push(key);
  }
}

方式二:使用Map的forEach方法

const trueKeys: string[] = [];
const falseKeys: string[] = [];

myMap.forEach((value, key) => {
  value ? trueKeys.push(key) : falseKeys.push(key);
});

这两种方法都只需要遍历一次Map的所有条目。你原来的实现里,每次通过[...myMap.entries()]生成数组都会遍历一次Map,再加上filter和map各自的遍历,总共会产生多次重复遍历的开销;而上面的方法一次遍历就能完成分组,效率更高。

内容的提问来源于stack exchange,提问作者user17365408

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:01:19