数组去重的常见方法

  有多种方法可以实现数组去重

  1. 使用Set
  2. 使用filter方法
  3. 使用reduce方法
  4. 使用for循环和indexOf方法
  5. 使用Map
  6. 使用includes方法
  7. 使用递归


1_使用Set

  ES6中的Set对象是一种无重复值的有序列表。通过将数组转换为Set对象,可以去除重复的元素,然后再将Set对象转换回数组。

<script>
        const array = [1, 2, 3, 3, 4, 5, 5];
        const uniqueArray = [...new Set(array)];
        console.log(uniqueArray);
    </script>

2_使用filter方法

  利用数组的filter方法,遍历数组并筛选出没有重复出现的元素。

const array = [1, 2, 3, 3, 4, 5, 5];
        const uniqueArray = array.filter((value, index, self) => {
            return self.indexOf(value) === index;
        });
        console.log(uniqueArray);

3_使用reduce方法

  利用reduce方法,遍历数组并将不重复的元素添加到一个新数组中

const array = [1, 2, 3, 3, 4, 5, 5];
        const uniqueArray = array.reduce((prev, curr) => {
            if (!prev.includes(curr)) {
                prev.push(curr);
            }
            return prev;
        }, []);
        console.log(uniqueArray);

4_使用for循环和indexOf方法

  通过遍历数组,判断元素在之前的部分是否已经出现过,若没有出现过,则添加到新数组中。

const array = [1, 2, 3, 3, 4, 5, 5];
        const uniqueArray = array.reduce((prev, curr) => {
            if (!prev.includes(curr)) {
                prev.push(curr);
            }
            return prev;
        }, []);
        console.log(uniqueArray);

5_使用Map

  利用Map对象的键值对特性,遍历数组并将元素作为键存储到Map中,然后再将Map的键转换为数组。

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

6_使用includes方法

  通过遍历数组,利用includes方法判断元素是否已经在新数组中存在,若不存在则添加到新数组中。

const array = [1, 2, 3, 3, 4, 5, 5];
        const uniqueArray = [];
        for (let i = 0; i < array.length; i++) {
            if (!uniqueArray.includes(array[i])) {
                uniqueArray.push(array[i]);
            }
        }
        console.log(uniqueArray);

7_使用递归

  逐个遍历数组的元素,如果元素在后面的部分中还出现过,则跳过,直到遍历完所有元素。

const array = [1, 2, 3, 3, 4, 5, 5];
        function unique(array) {
            if (array.length === 1) {
                return array;
            }
            const first = array[0];
            const rest = unique(array.slice(1));
            if (rest.includes(first)) {
                return rest;
            } else {
                return [first, ...rest];
            }
        }
        const uniqueArray = unique(array);
        console.log(uniqueArray);

根据不同的场景和需求选择适合

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇敢的茂密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值