数组去重方法

✅ 一、最简单(推荐首选)

👉 使用 Set(ES6)

复制代码
const arr = [1, 2, 2, 3, 4, 4];

const result = [...new Set(arr)];

console.log(result); // [1, 2, 3, 4]

✔ 优点:

  • 写法最简洁

  • 性能好(接近 O(n))

✔ 缺点:

  • 无法处理对象去重(引用不同)

✅ 二、使用 filter

复制代码
const arr = [1, 2, 2, 3, 4, 4];

const result = arr.filter((item, index) => {
  return arr.indexOf(item) === index;
});

console.log(result);

✔ 原理:

  • 只保留第一次出现的位置

❗ 缺点:

  • 性能较差(O(n²))

✅ 三、使用 reduce

复制代码
const arr = [1, 2, 2, 3, 4, 4];

const result = arr.reduce((acc, cur) => {
  if (!acc.includes(cur)) {
    acc.push(cur);
  }
  return acc;
}, []);

console.log(result);

✔ 适合理解函数式编程


✅ 四、使用 Map(推荐处理复杂数据)

复制代码
const arr = [1, 2, 2, 3, 4, 4];

const map = new Map();
const result = [];

arr.forEach(item => {
  if (!map.has(item)) {
    map.set(item, true);
    result.push(item);
  }
});

console.log(result);

✔ 优点:

  • 性能好

  • 可扩展(对象去重)


🚀 五、对象数组去重(面试重点🔥)

👉 按某个字段去重

复制代码
const arr = [
  { id: 1, name: 'a' },
  { id: 1, name: 'b' },
  { id: 2, name: 'c' }
];

const map = new Map();

const result = arr.filter(item => {
  if (!map.has(item.id)) {
    map.set(item.id, true);
    return true;
  }
  return false;
});

console.log(result);

🧠 六、终极通用写法(封装函数)

复制代码
function unique(arr, key) {
  const map = new Map();

  return arr.filter(item => {
    const value = key ? item[key] : item;

    if (!map.has(value)) {
      map.set(value, true);
      return true;
    }
    return false;
  });
}

使用👇

复制代码
unique([1, 2, 2, 3]); 
unique([{id:1},{id:1}], 'id');

⚠️ 七、面试加分点(必须知道)

1️⃣ Set 去重不了对象

复制代码
[{a:1}, {a:1}] // ❌ 还是两个

原因:

👉 引用地址不同


2️⃣ 性能排序(面试常问)

方法 时间复杂度
Set ⭐ O(n)
Map ⭐ O(n)
filter ❌ O(n²)
includes ❌ O(n²)

3️⃣ 特殊值问题

复制代码
NaN === NaN // false

👉 但:

复制代码
new Set([NaN, NaN]) // ✅ 只保留一个

✍️ 总结一句话

👉 简单数据用 Set,复杂数据用 Map,面试优先讲这两个

相关推荐
晴天的雨.9922 小时前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
开开心心就好5 小时前
批量提取PDF中的图片,直接导出原图
前端·javascript·支持向量机·智能手机·pdf·html·启发式算法
IvanCodes7 小时前
Python 数据处理(十三):JSON、CSV 与数据序列化
开发语言·python
Setsuna_F_Seiei8 小时前
前端转型 Agent 开发 05 之 Agent Hooks 与 Checkpointer(让 Agent 从全自动转变人为可掌控)
前端·agent·ai编程
aramae9 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法
百万蹄蹄向前冲9 小时前
风扇转了一晚上MVP专家团翻车事故
前端·人工智能
默_笙10 小时前
🏛 给 AI 配一间办公室:Harness Engineering 六大模块与它的实现
前端·javascript
linux_cfan11 小时前
videojs v10 源代码系列解读:14 · 谓词守卫:在运行时安全地调用能力
前端·javascript·音视频
qq_25183645711 小时前
springboot vue3 开发实现 拼豆管理系统
java·开发语言·ai编程
kyriewen11 小时前
我扒了 10,221 条 JD:腾讯技术岗 75% 在要 AI
前端·人工智能·ai编程