如何在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; }); })();
实现逻辑说明
- 用立即执行函数(IIFE)封装
Set状态,确保这个跟踪集合仅在数组转换过程中生效,不会干扰外部代码 - 遍历数组时,先检查当前数字是否已存在于
seen集合中 - 根据是否重复,生成对应的
string字段内容 - 每次处理完元素后,将当前数字加入
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
相关产品推荐
相关产品推荐

