答案:JavaScript中可用reduce结合对象或Map实现数组去重,基本类型通过seen标记已存在值,对象数组按指定字段(如id)判断唯一性,累加器保存状态并返回去重结果。

在JavaScript中,可以使用 reduce() 方法结合对象或Map来实现数组去重。这种方法适用于基本类型数组(如数字、字符串)以及对象数组的去重。
利用 reduce 遍历数组,通过一个对象记录已出现的值,避免重复添加。
const arr = [1, 2, 2, 3, 4, 4, 5]; const unique = arr.reduce((acc, current) => { if (!acc.seen[current]) { acc.seen[current] = true; acc.result.push(current); } return acc; }, { seen: {}, result: [] }).result; console.log(unique); // [1, 2, 3, 4, 5]说明:使用一个对象 seen 来标记元素是否已存在,保证唯一性,最终返回 result 数组。
如果要去重的对象数组中有重复的某个属性(如 id),可以用 reduce 按该字段判断是否已存在。
const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice' } ]; const uniqueUsers = users.reduce((acc, current) => { if (!acc.map[current.id]) { acc.map[current.id] = true; acc.result.push(current); } return acc; }, { map: {}, result: [] }).result; console.log(uniqueUsers); // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]说明:以 id 为唯一标识,通过 map 记录已添加的 id,避免重复插入。
虽然题目要求用 reduce,但值得一提的是,对于基本类型,更简洁的方式是使用 Set:
const unique = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]但在需要复杂逻辑(如对象去重)时,reduce 提供了更大的灵活性。
基本上就这些。reduce 实现去重的关键是利用累加器保存状态(如 seen 或 map),一边遍历一边判断是否已存在。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号