• 数组去重有哪些方法


    在JavaScript中,有多种方法可以用于数组去重,以下是一些常见的方法:

    使用SetES6引入了Set数据结构,它只允许存储唯一的值,因此可以用来去重数组。

    1. const array = [1, 2, 2, 3, 4, 4, 5];
    2. const uniqueArray = [...new Set(array)];

    使用filter:使用filter方法和indexOfincludes来创建一个新的数组,只包含不重复的元素。

    1. const array = [1, 2, 2, 3, 4, 4, 5];
    2. const uniqueArray = array.filter((item, index, self) => self.indexOf(item) === index);

    使用reduce:使用reduce方法来构建一个新的数组,只包含不重复的元素。

    1. const array = [1, 2, 2, 3, 4, 4, 5];
    2. const uniqueArray = array.reduce((accumulator, current) => {
    3. if (!accumulator.includes(current)) {
    4. accumulator.push(current);
    5. }
    6. return accumulator;
    7. }, []);

    使用forEach:使用forEach循环遍历原始数组,将不重复的元素添加到一个新数组。

    1. const array = [1, 2, 2, 3, 4, 4, 5];
    2. const uniqueArray = [];
    3. array.forEach(item => {
    4. if (!uniqueArray.includes(item)) {
    5. uniqueArray.push(item);
    6. }
    7. });

    使用对象属性:创建一个空对象,以数组元素的值为属性,并检查属性是否已存在来去重。

    1. const array = [1, 2, 2, 3, 4, 4, 5];
    2. const uniqueArray = {};
    3. array.forEach(item => {
    4. uniqueArray[item] = true;
    5. });
    6. const result = Object.keys(uniqueArray).map(Number);

    虽然Map主要用于键值对的存储和检索,但你也可以使用Map来去重数组,虽然不是最常见的做法。

    下面是一个使用Map来去重数组的示例:

    1. const array = [1, 2, 2, 3, 4, 4, 5];
    2. const uniqueArray = Array.from(new Map(array.map(item => [item, item])).values());

    在上面的示例中,我们使用array.map方法将数组元素映射为键值对的数组,然后使用new Map来创建一个Map,确保键的唯一性。最后,通过Array.fromMap.values()方法,我们将Map中的唯一值提取出来,从而得到去重后的数组。

    虽然这种方法可以去重数组,但通常来说,Set更适合这种任务,因为它的主要目的就是存储唯一的值。Map更适用于需要存储键值对的场景,如关联数据或字典。

  • 相关阅读:
    java中的反射机制
    【Vue框架】vue组件的生命周期
    2023/10/4 -- ARM
    ElasticSearch7.3学习(九)----Mapping核心数据类型及dynamic mapping
    QT之excel的读写
    【Arduino+ESP32专题】案例:串口接收字符串并按指定分隔符分割
    ASP.NET CORE 项目搭建(2022 年 3 月版)[一]
    react hook
    TCP/IP协议详解
    分词算法----正向和逆向最大匹配算法(含Python代码实现)
  • 原文地址:https://blog.csdn.net/coinisi_li/article/details/133926126