JS对于数组去重都有哪些方法?

JavaScript(JS)中有多种方法可以实现数组去重。以下是一些常见的方法:

  1. 使用 Set 对象
    Set 对象是一个集合,它存储唯一值,自动去重。这是一个简单且高效的方法。

    javascript 复制代码
    const array = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArray = [...new Set(array)];
    console.log(uniqueArray); // [1, 2, 3, 4, 5]
  2. 使用 filterindexOf 方法

    通过 filter 方法结合 indexOf 来检查元素是否在数组中的特定位置。

    javascript 复制代码
    const array = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
    console.log(uniqueArray); // [1, 2, 3, 4, 5]
  3. 使用 reduce 方法

    使用 reduce 方法构建一个新的数组,同时确保每个元素都是唯一的。

    javascript 复制代码
    const array = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArray = array.reduce((accumulator, currentValue) => {
      if (accumulator.indexOf(currentValue) === -1) {
        accumulator.push(currentValue);
      }
      return accumulator;
    }, []);
    console.log(uniqueArray); // [1, 2, 3, 4, 5]
  4. 使用对象(Object)或 Map

    通过将数组元素作为对象的键来实现去重。

    javascript 复制代码
    const array = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArray = Array.from(new Map(array.map((item) => [item, 1]))).map(item => item[0]);
    console.log(uniqueArray); // [1, 2, 3, 4, 5]
  5. 排序后去重

    对数组进行排序,然后去除相邻的重复项。

    javascript 复制代码
    const array = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArray = [...new Set(array.sort((a, b) => a - b))];
    console.log(uniqueArray); // [1, 2, 3, 4, 5]
  6. 使用扩展运算符(...)和 join / split

    这是一种比较不常见的方法,利用字符串的 joinsplit 方法来去重。

    javascript 复制代码
    const array = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArray = [...new Set(array.join(',').split(',').map(Number))];
    console.log(uniqueArray); // [1, 2, 3, 4, 5]

选择哪种方法取决于具体需求和数组的特点。例如,如果需要保持数组的原始顺序,则可能需要避免使用排序方法。如果数组很大,那么 Set 方法可能更高效。

相关推荐
gis开发之家14 分钟前
《Vue3 从入门到大神29篇》单元测试与 E2E 测试 —— 保障 Vue3 项目的质量
前端·javascript·vue.js·单元测试·前端框架·vue3
爱勇宝22 分钟前
AI 时代,更稀缺的是「提出好问题」还是「判断好答案」?
前端·人工智能·后端
李伟_Li慢慢23 分钟前
three.js 中的WebGPU 有几成熟了?
前端·three.js
逝水无殇24 分钟前
C# 正则表达式详解
开发语言·后端·正则表达式·c#
阿酷tony25 分钟前
纯HTML5播放器带倍速、带画质切换的播放器
前端·html·html5
ShiXZ21331 分钟前
指令集-NPM 常用指令速查手册
前端·npm·node.js
朱永博36 分钟前
使用Onnruntime实现Padim/Patchcore推理
开发语言·c#
এ慕ོ冬℘゜37 分钟前
前端核心知识体系进阶:从安全机制、网络协议到原生 JS 实战全解析
前端·网络协议·安全
前端H38 分钟前
Biome & Rolldown:Rust 工具链接管前端基建
开发语言·前端·rust
柒和远方41 分钟前
从等待到流式:LLM 流式输出的原理、协议与工程实践
javascript·llm