数组去重5种方法

1. 双重for循环,设置一个变量为没有重复的状态,如果有相同的值则跳过,不相同就push进数组

2.遍历数组,建立新数组,利用indexOf判断是否存在于新数组中,不存在就push到新数组中

3.用lastIndexOf和indexOf查找

4.利用set成员唯一性进行去重

5. 利用对象属性不能重复进行数组去重

 

  • 4
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure! 下面是常见的6JavaScript数组去重方法: 1. 使用Set数据结构:Set是ES6引入的一新的数据结构,它可以自动去除重复的值。 ```javascript const array = [1, 2, 3, 3, 4, 5, 5]; const uniqueArray = [...new Set(array)]; console.log(uniqueArray); ``` 2. 使用filter方法:使用filter方法遍历数组,然后通过indexOf判断当前元素在数组中的索引和当前索引是否相等,如果相等则保留,否则去除。 ```javascript 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方法遍历数组,将每个元素放入一个新数组中,同时使用includes方法判断新数组中是否已存在该元素。 ```javascript const array = [1, 2, 3, 3, 4, 5, 5]; const uniqueArray = array.reduce((acc, currentValue) => { if (!acc.includes(currentValue)) { acc.push(currentValue); } return acc; }, []); console.log(uniqueArray); ``` 4. 使用Map数据结构:使用Map数据结构可以根据键的唯一性去除重复值。 ```javascript const array = [1, 2, 3, 3, 4, 5, 5]; const uniqueArray = Array.from(new Map(array.map(value => [value, value])).values()); console.log(uniqueArray); ``` 5. 使用递归:使用递归来遍历数组,然后判断当前元素是否在之前的元素中出现过。 ```javascript const array = [1, 2, 3, 3, 4, 5, 5]; function unique(array) { if (array.length === 1) { return array; } if (array.slice(1).includes(array

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值