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

相关推荐
Hexene...几秒前
【前端Vue】如何实现echarts图表根据父元素宽度自适应大小
前端·vue.js·echarts
nananaij2 分钟前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
初遇你时动了情2 分钟前
腾讯地图 vue3 使用 封装 地图组件
javascript·vue.js·腾讯地图
dssxyz6 分钟前
uniapp打包微信小程序主包过大问题_uniapp 微信小程序时主包太大和vendor.js过大
javascript·微信小程序·uni-app
阿蒙Amon12 分钟前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
无小道14 分钟前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++
爱莉希雅&&&22 分钟前
技术面试题,HR面试题
开发语言·学习·面试
天天扭码36 分钟前
《很全面的前端面试题》——HTML篇
前端·面试·html
xw537 分钟前
我犯了错,我于是为我的uni-app项目引入环境标志
前端·uni-app
!win !40 分钟前
被老板怼后,我为uni-app项目引入环境标志
前端·小程序·uni-app