如何实现JavaScript数组去重_有哪些高效的去重方法

推荐使用 Set 去重,简洁高效且保持顺序;兼容旧环境可用 filter + indexOf;对象数组需按字段(如 id)去重,可用 findIndex 或 Map 缓存。

JavaScript 数组去重有多种方法,效率和适用场景各不相同。现代开发中推荐优先使用 Set,兼顾简洁性与性能;若需兼容旧环境或自定义逻辑(如对象数组去重),则可选 filter + indexOfreduce 或 Map 辅助方案。

用 Set 最快最简洁(推荐)

Set 是 ES6 引入的原生数据结构,自动忽略重复值,转回数组只需一行代码:

const arr = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(arr)]; // [1, 2, 3, 4, 5]
  • 时间复杂度接近 O(n),内部基于哈希实现,查找去重极快
  • 只适用于原始类型(number/string/boolean/symbol/undefined/null),对对象引用无效
  • 会保持原始顺序,且不修改原数组

filter + indexOf(兼容性好,适合简单数组)

利用 indexOf 返回首次出现索引的特性,保留第一次出现的元素:

const arr = [1, 2, 2, 3, 4, 4, 5];
const unique = arr.filter((item, index) => arr.indexOf(item) === index);
  • 兼容 IE9+,无需额外 polyfill
  • 对原始类型有效,但时间复杂度为 O(n²),大数据量时明显变慢
  • 同样保持原顺序

reduce + includes(语义清晰,适合新手理解)

reduce 累积结果数组,每次检查是否已存在:

立即学习“Java免费学习笔记(深入)”;

const arr = [1, 2, 2, 3, 4, 4, 5];
const unique = arr.reduce((acc, item) => {
  return acc.includes(item) ? acc : [...acc, item];
}, []);
  • 逻辑直观,容易调试和扩展
  • includes 在大数组中逐项查找,性能不如 Set
  • 注意:每次展开数组([...acc, item])会产生新数组,内存开销略高

处理对象数组(按字段去重)

原始方法无法直接比较对象,需提取唯一标识(如 id、name):

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' }
];

const uniqueUsers = users.filter((user, index, self) =>
  index === self.findIndex(item => item.id === user.id)
);
  • findIndex 定位第一个匹配项,保留首次出现的对象
  • 更高效写法可用 Map 缓存已见 key:users.reduce((map, item) => map.has(item.id) ? map : map.set(item.id, item), new Map()).values()
  • 避免深比较(如整个对象内容一致),除非明确需要,否则性能代价大
不复杂但容易忽略细节:去重前先确认数据类型、是否需保留顺序、是否要兼容老浏览器,再选方法。