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

相关推荐
陈皮话梅糖@2 小时前
使用 Provider 和 GetX 实现 Flutter 局部刷新的几个示例
开发语言·javascript·flutter
hvinsion3 小时前
基于PyQt5的自动化任务管理软件:高效、智能的任务调度与执行管理
开发语言·python·自动化·自动化任务管理
Aphelios3803 小时前
Java全栈面试宝典:线程机制与Spring IOC容器深度解析
java·开发语言·jvm·学习·rbac
qq_529835353 小时前
装饰器模式:如何用Java打扮一个对象?
java·开发语言·装饰器模式
日暮南城故里3 小时前
Java学习------源码解析之StringBuilder
java·开发语言·学习·源码
Vitalia4 小时前
从零开始学Rust:枚举(enum)与模式匹配核心机制
开发语言·后端·rust
双叶8364 小时前
(C语言)虚数运算(结构体教程)(指针解法)(C语言教程)
c语言·开发语言·数据结构·c++·算法·microsoft
Yolo@~6 小时前
个人网站:基于html、css、js网页开发界面
javascript·css·html
斯~内克6 小时前
Electron 菜单系统深度解析:从基础到高级实践
前端·javascript·electron
一个public的class6 小时前
什么是 Java 泛型
java·开发语言·后端