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

相关推荐
玲小珑1 分钟前
Auto.js 入门指南(六)多线程与异步操作
android·前端
白瓷梅子汤4 分钟前
跟着官方示例学习 @tanStack-table --- Header Groups
前端·react.js
喝牛奶的小蜜蜂8 分钟前
个人小程序:不懂后台,如何做数据交互
前端·微信小程序·小程序·云开发
front_explorers13 分钟前
Umi项目必看,从Webpack到Rspack,KMI引领性能革命🚀
前端
旺仔牛仔QQ糖14 分钟前
都写那么多项目了, 傻傻分不清楚NODE_ENV 和 模式(Mode) 两者区别是什么
前端·面试
xcLeigh19 分钟前
HTML5实现简洁的体育赛事网站源码
前端·html
渔舟唱晚@21 分钟前
Axios 取消请求的演进:CancelToken vs. AbortController
javascript
棉花糖超人22 分钟前
【从0-1的CSS】第1篇:CSS简介,选择器已经常用样式
前端·css
GISer_Jing27 分钟前
XHR / Fetch / Axios 请求的取消请求与请求重试
前端·javascript·网络
天涯学馆30 分钟前
微前端架构设计:从理论到实践的全面指南
前端·javascript·面试