数组去重的六种方法

方法一、

使用for循环,双层遍历,当内层循环的值等于外层循环的值,则将内层循环的值,使用 splice() 删除

方法二、

使用 Set() 将 arr 去重后,再转换为数组

方法三、

indexOf() 方法返回某个指定的字符串值在字符串中首次出现的位置,如果没有找到匹配的字符串则返回 -1

方法四、

includes() 方法用于判断字符串是否包含指定的子字符串。如果找到匹配的字符串则返回 true ,否则返回 false

方法五、

set() 方法为 Map() 对象添加或更新一个指定了键( key )和值( value )的(新)键值对

方法六、

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure! 下面是常见的6种JavaScript数组方法: 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、付费专栏及课程。

余额充值