技术知识文章集合TECHNICAL ARCHIVE · 457 DOCUMENTS

显示模式

登录
ARCHIVE DOCUMENTJS

解锁多种JavaScript数组去重姿势

所属馆藏
JavaScript
文件格式
Markdown
原始路径
JavaScript/122-解锁多种JavaScript数组去重姿势
本文目录10 个章节
  1. 双重循环
  2. Array.prototype.indexOf()
  3. Array.prototype.sort()
  4. Array.prototype.includes()
  5. Array.prototype.reduce()
  6. 对象键值对
  7. Map
  8. Set
  9. 总结
  10. 2025 视角:现在该怎么选

解锁多种JavaScript数组去重姿势

Category(分类): JavaScript Status: 已审查(2025)

原文:小渐,《解锁多种JavaScript数组去重姿势》,稀土掘金(2018)。本文在保留原文全部实现与结论的基础上,修正了个别表述,并补充了现代视角(Set 已是首选、NaN 与引用类型的去重语义、WeakSet 等)。

JavaScript数组去重,一个老生常谈的问题了,但这次是解锁多种JavaScript数组去重姿势。

对以下所有的实现算法,都使用以下代码进行粗略测试:

const arr = [];
// 生成 [0, 100000] 之间的随机整数
for (let i = 0; i < 100000; i++) {
  arr.push(0 + Math.floor((100000 - 0 + 1) * Math.random()))
}

// ... 实现算法
console.time('test');
arr.unique();
console.timeEnd('test');

⚠️ 下文各实现附带的耗时数字全部来自原文作者 2018 年的浏览器环境,绝对值在今天没有参考意义,只能用来比较各算法之间的相对量级(双重循环是 O(n²),哈希类结构是 O(n))。

另外教学代码把 unique 挂到了 Array.prototype 上,方便统一测试;实际项目中不要污染内置原型,用普通函数 unique(arr) 即可。

双重循环

双重循环去重实现比较容易。

实现一:

Array.prototype.unique = function () {
  const newArray = [];
  let isRepeat;
  for (let i = 0; i < this.length; i++) {
    isRepeat = false;
    for (let j = 0; j < newArray.length; j++) {
      if (this[i] === newArray[j]) {
        isRepeat = true;
        break;
      }
    }
    if (!isRepeat) {
      newArray.push(this[i]);
    }
  }
  return newArray;
}

实现二(内层改为向后扫描原数组,遇到重复则跳过当前项。注意:它与实现一结果不同——保留的是每个重复项的最后一次出现,而不是第一次):

Array.prototype.unique = function () {
  const newArray = [];
  let isRepeat;
  for (let i = 0; i < this.length; i++) {
    isRepeat = false;
    for (let j = i + 1; j < this.length; j++) {
      if (this[i] === this[j]) {
        isRepeat = true;
        break;
      }
    }
    if (!isRepeat) {
      newArray.push(this[i]);
    }
  }
  return newArray;
}

基于思路二的写法改进版,实现三:

Array.prototype.unique = function () {
  const newArray = [];

  for (let i = 0; i < this.length; i++) {
    for (let j = i + 1; j < this.length; j++) {
      if (this[i] === this[j]) {
        j = ++i;
      }
    }
    newArray.push(this[i]);
  }
  return newArray;
}

实现三比较绕:发现 this[i] 与后面重复时,直接把外层游标推进到重复段的最后一位(j = ++i),让内层循环从那继续找。效果与实现二相同,代码更短但可读性更差。

经过测试代码测试的时间如下(2018 年环境,10 万条数据):

test1: 3688.440185546875ms
test2: 4641.60498046875ms
test3: 17684.365966796875ms

Array.prototype.indexOf()

基本思路:如果索引不是第一个索引,说明是重复值。

实现一:

  • 利用Array.prototype.filter()过滤功能
  • Array.prototype.indexOf()返回的是第一个索引值
  • 只将数组中元素第一次出现的返回
  • 之后出现的将被过滤掉
Array.prototype.unique = function () {
  return this.filter((item, index) => {
    return this.indexOf(item) === index;
  })
}

实现二:

let arr = [1, 2, 3, 22, 233, 22, 2, 233, 'a', 3, 'b', 'a'];
Array.prototype.unique = function () {
  const newArray = [];
  this.forEach(item => {
    if (newArray.indexOf(item) === -1) {
      newArray.push(item);
    }
  });
  return newArray;
}

经过测试代码测试的时间如下:

test1: 4887.201904296875ms
test2: 3766.324951171875ms

Array.prototype.sort()

基本思路:先对原数组进行排序,然后再进行元素比较。

实现一:

Array.prototype.unique = function () {
  const newArray = [];
  this.sort();
  for (let i = 0; i < this.length; i++) {
    if (this[i] !== this[i + 1]) {
      newArray.push(this[i]);
    }
  }
  return newArray;
}

实现二:

Array.prototype.unique = function () {
  const newArray = [];
  this.sort();
  for (let i = 0; i < this.length; i++) {
    if (this[i] !== newArray[newArray.length - 1]) {
      newArray.push(this[i]);
    }
  }
  return newArray;
}

经过测试代码测试的时间如下:

test1: 121.6259765625ms
test2: 123.02197265625ms

⚠️ 注意两个副作用:

  1. this.sort()原地排序,会直接修改原数组的顺序(上面的实现都破坏了原数组);不想破坏原数组应先 [...this].sort()
  2. 无参 sort() 按字符串码位排序,数字 10 会排在 2 前面。对"去重"本身没影响(重复值一定相邻),但输出顺序不是数值序。

Array.prototype.includes()

Array.prototype.unique = function () {
  const newArray = [];
  this.forEach(item => {
    if (!newArray.includes(item)) {
      newArray.push(item);
    }
  });
  return newArray;
}

经过测试代码测试的时间如下:

test: 4123.377197265625ms

includesindexOf 的一个重要差别:includes 使用 SameValueZero 比较,能找到 NaN[NaN].includes(NaN) === true);而 indexOf 用严格相等,NaN 永远找不到(NaN !== NaN)。这带来两种截然不同的 NaN 行为:

  • filter + indexOf 版(上面的实现一)会把所有 NaN 全部删掉this.indexOf(NaN) 恒为 -1-1 !== index 恒为真,每个 NaN 都被 filter 掉;
  • indexOf-push 版(下面的实现二)会把重复的 NaN 全部保留newArray.indexOf(NaN) 恒为 -1,每个 NaN 都被 push;
  • includes 版可以正确去掉重复的 NaN(保留一个)。

双重循环版(=== 比较)与 indexOf-push 版一样,会保留所有 NaN;而 Set/Map/对象键值对法都会把 NaN 去成一个。

Array.prototype.reduce()

Array.prototype.unique = function () {
  return this.sort().reduce((init, current) => {
    if(init.length === 0 || init[init.length - 1] !== current){
      init.push(current);
    }
    return init;
  }, []);
}

经过测试代码测试的时间如下:

test: 180.401123046875ms

对象键值对

基本思路:利用了对象的 key 不可以重复的特性来进行去重。

但需要注意:

  • 无法区分隐式类型转换成字符串后一样的值,比如 1'1'
  • 无法处理复杂数据类型,比如对象(因为对象作为 key 会变成 [object Object]
  • 特殊数据,比如 '__proto__',因为对象的 __proto__ 属性无法被重写

解决第一、第三点问题,实现一(用 typeof 值做前缀,同时天然避开了 '__proto__' 这种撞上原型 setter 的键):

Array.prototype.unique = function () {
  const newArray = [];
  const tmp = {};
  for (let i = 0; i < this.length; i++) {
    if (!tmp[typeof this[i] + this[i]]) {
      tmp[typeof this[i] + this[i]] = 1;
      newArray.push(this[i]);
    }
  }
  return newArray;
}

解决第二点问题,实现二:

Array.prototype.unique = function () {
  const newArray = [];
  const tmp = {};
  for (let i = 0; i < this.length; i++) {
    // 使用JSON.stringify()进行序列化
    if (!tmp[typeof this[i] + JSON.stringify(this[i])]) {
      // 将对象序列化之后作为key来使用
      tmp[typeof this[i] + JSON.stringify(this[i])] = 1;
      newArray.push(this[i]);
    }
  }
  return newArray;
}

经过测试代码测试的时间如下:

test1: 113.849365234375ms
test2: 157.030029296875ms

JSON.stringify 方案的边界:JSON.stringify(/a/) === '{}',与 {} 的序列化结果相同,所以正则对象之间会被"误判为相等"而只保留第一个;此外对象键的顺序不同({a:1,b:2} vs {b:2,a:1})也会被判为不相等。它只适合结构已知、键顺序稳定的场景。

Map

实现一:

Array.prototype.unique = function () {
  const newArray = [];
  const tmp = new Map();
  for(let i = 0; i < this.length; i++){
        if(!tmp.get(this[i])){
            tmp.set(this[i], 1);
            newArray.push(this[i]);
        }
    }
    return newArray;
}

实现二:

Array.prototype.unique = function () {
  const tmp = new Map();
  return this.filter(item => {
    return !tmp.has(item) && tmp.set(item, 1);
  })
}

实现二里的 !tmp.has(item) && tmp.set(item, 1) 是个利用短路求值的技巧:Map.set() 返回 Map 实例本身(真值),所以整条表达式在"首次遇到"时返回真值让 filter 放行,之后 has 命中直接短路为 false

经过测试代码测试的时间如下:

test1: 27.89697265625ms
test2: 21.945068359375ms

Set

Array.prototype.unique = function () {
  const set = new Set(this);
  return Array.from(set);
}
Array.prototype.unique = function () {
  return [...new Set(this)];
}

经过测试代码测试的时间如下:

test1: 36.8046875ms
test2: 31.98681640625ms

总结

除了考虑时间复杂度外、性能之外,还要考虑数组元素的数据类型(例如下面的例子)等问题权衡选择出采用哪种算法,例如:

const arr = [1, 1, '1', '1', 0, 0, '0', '0', undefined, undefined, null, null, NaN, NaN, {}, {}, [], [], /a/, /a/];

原文当时得出的结论是"经过综合考虑,最优的数组去重算法是采用 Map 数据结构实现的算法"——在 2018 年的测试环境里 Map 确实跑得最快。但放在今天,这个结论应当更新:

2025 视角:现在该怎么选

  1. 默认答案就是 Set[...new Set(arr)]Array.from(new Set(arr))。一行、零依赖、O(n),且 V8 多年来对 Set 的构造和迭代做了大量优化,如今它与 Map 方案的性能差距可以忽略(常常不分胜负)。Map 方案在"谁最快"上的历史优势已经不再构成选择它的理由。
  2. NaN 的语义要心里有数Set/Map 使用 SameValueZero 比较,NaN 算作重复会被去掉;indexOf/filter 方案用严格相等,重复的 NaN 会全部保留;includes 方案能去 NaN
  3. 引用类型永远去不了重{} !== {},上面所有方法(除了 JSON.stringify 那种内容近似比较)对两个内容相同的不同对象引用都会原样保留——这不是 bug,是引用语义。要对"对象数组按内容去重",先想清楚业务键(比如 id):
// users 形如 [{id:1},{id:2},{id:1}],结果保留前两个
const seen = new Set();
const unique = users.filter(u => !seen.has(u.id) && seen.add(u.id));
  1. 对象引用去重用 WeakSet/WeakMap:只想判断"同一个对象是否出现过",用 WeakSet 更合适,它不阻止垃圾回收:
const seen = new WeakSet();
const unique = objs.filter(o => !seen.has(o) && seen.add(o));
  1. 要保留重复项中最后一个(或最先出现顺序之外的规则)时Map 反而更好用——new Map(arr.map(x => [key(x), x])).values() 天然"后者覆盖前者"。
  2. 不要污染 Array.prototype:教学代码里的 arr.unique() 写法在真实项目里应换成独立函数,避免与第三方库/未来原生方法冲突。

一句话:普通数组去重,[...new Set(arr)];按业务键去重,Set/Mapfilter;涉及对象引用用 WeakSet

作者:小渐 链接:https://juejin.cn/post/6844903608467587085 来源:稀土掘金 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

457 DOCUMENTS · 10 COLLECTIONS
ARCHIVE SEARCH457 篇文章

SEARCH GUIDE

输入关键词开始搜索

支持搜索文章标题、所属分类和原始文档路径。

按分类浏览

10 COLLECTIONS