使用Set进行数组去重
关键词:ES6,set,Array.from(set),[...set],数组去重
使用Set进行数组去重方法,如下:
const arr = new Set([1,2,3,4,4,5])
[...arr]
// 去重,返回[1,2,3,4,5]
const arr = new Set([1,2,3,4,4,5])
Array.from(arr)
// 去重,返回[1,2,3,4,5]
Set 概述
Set是ES6提供的新的数据结构,它类似于数组。但是它的成员都是独一无二的,没有重复的值。根据它的这个特点,可以用来对数组进行去重操作。可以按照插入的顺序迭代其中的元素。Set 语法
new Set([iterable])
// 返回一个新的Set对象
其他的数组去重方法
let arr = [1,2,3,4,4,5]// 1. 只用循环的方式
Array.prototype.unique1 = function () {
let res = [] // 存放去重后的数组
let mark = {} // 用来检测重复的值
for (let i = 0, arrayLen = this.length;
i < arrayLen;
i++) {
if (!mark[this[i]]) {
res.push(this[i])
mark[this[i]] = true
} else {
console.log(`重复的值是:${this[i]}`)
}
}
return res
}// 2. 使用indexOf()
Array.prototype.unique2 = function () {
let res = [] // 存放去重后的数组
for (let i = 0, arrayLen = this.length;
i < arrayLen;
i++) {
// 如果this[i]没有在res中,则push进去
if (res.indexOf(this[i]) === -1) {
res.push(this[i])
}
}
return res
}// 3. 使用sort()先进行排序,如果当前元素与前一个元素相同,则为重复的元素
Array.prototype.unique3 = function () {
// 存放去重后的数组
// 把目标数组的第一个元素放进去,后面的循环从目标数组的第二个元素开始
let res = [this[0]]
// 在原目标数组的基础上进行排序
this.sort()
for (let i = 1, arrayLen = this.length;
i < arrayLen;
i++) {
if (this[i] !== this[i-1]) {
res.push(this[i])
}
}
return res
}
arr.unique1() // [1, 2, 3, 4, 5]
arr.unique2() // [1, 2, 3, 4, 5]
arr.unique3() // [1, 2, 3, 4, 5]
【使用Set进行数组去重】---end---
推荐阅读
- 由浅入深理解AOP
- 【译】20个更有效地使用谷歌搜索的技巧
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- MybatisPlus使用queryWrapper如何实现复杂查询
- iOS中的Block
- Linux下面如何查看tomcat已经使用多少线程
- 使用composer自动加载类文件
- android|android studio中ndk的使用
- 使用协程爬取网页,计算网页数据大小