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

如何在JavaScript的.map()遍历中判断新数组是否已存在值?

函数式实现:用.map()转换数组并标记重复元素

可以通过闭包封装状态的方式实现,既保留map的函数式特性,又能跟踪已出现的数字,避免使用空数组push的写法:

const data = [1, 2, 3, 2, 4];
type NewData = {
    string: string;
    number: number;
};

const test: NewData[] = (() => {
  // 用Set维护已处理过的数字,避免污染外部作用域
  const seen = new Set<number>();
  return data.map(num => {
    const isDuplicate = seen.has(num);
    const result = {
      string: isDuplicate ? `${num} is already there` : num.toString(),
      number: num
    };
    // 将当前数字加入集合,供后续元素判断重复
    seen.add(num);
    return result;
  });
})();

实现逻辑说明

  1. 用立即执行函数(IIFE)封装Set状态,确保这个跟踪集合仅在数组转换过程中生效,不会干扰外部代码
  2. 遍历数组时,先检查当前数字是否已存在于seen集合中
  3. 根据是否重复,生成对应的string字段内容
  4. 每次处理完元素后,将当前数字加入seen集合,保证后续重复项能被正确识别

执行后输出结果完全符合期望:

[
  {string: "1", number: 1},
  {string: "2", number: 2},
  {string: "3", number: 3},
  {string: "2 is already there", number: 2},
  {string: "4", number: 4}  
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:15:37