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 方法可能更高效。

相关推荐
筱璦8 分钟前
PHP+ VUE3机构级股票分仓管理交易系统源码可出
开发语言·php·vue3·量化·股票分仓
爱奥尼欧11 分钟前
10.C++ string 实现详解
java·开发语言·c++
骇客野人21 分钟前
Java分布式任务调度方案(完整落地指南)
java·开发语言·分布式
JacksonMx27 分钟前
Spring @Async 坑点 + 改造方案
java·开发语言
你怎么知道我是队长38 分钟前
IPv6 地址完全解析:从结构到实战
开发语言·php
Dovis(誓平步青云)1 小时前
牛奶不能减成负数:冰箱库存的筛选、去重与不可变更新
android·java·开发语言
OPEN-F1 小时前
Python进阶教程:算法与数据结构入门
开发语言·python
薛定猫AI1 小时前
【技术干货】Claude Code多模型代理与反馈闭环:Python实现可验证的AI编程工作流
开发语言·python·ai编程
XR1234567881 小时前
工厂车间无线网络怎么选?AGV 与复杂环境是分水岭
开发语言·php
zq_63891 小时前
利用 MATLAB 调用 STK Object Model COM 显示雷达受干扰前后探测范围的变化
开发语言·matlab