数组去重
AprilTong 11/17/2021 简单算法
# 数组去重
- 描述
为 Array 对象添加一个去除重复项的方法,题目链接 (opens new window)
- 例子
输入:[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
输出:[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']
1
2
3
2
3
# 自己实现
通过 Set 数据结构成员值唯一,没有重复值的特性实现 方法一:
Array.prototype.uniq = function() {
return Array.from(new Set(this))
}
1
2
3
2
3
方法二:
Array.prototype.uniq = function() {
return [...new Set(this)]
}
1
2
3
2
3
方法三:
Array.prototype.uniq = function() {
let result = []
this.forEach((el) => {
if (!result.includes(el)) {
result.push(el)
}
})
return result
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 讨论中别人比较好的实现
方法 1: 通过 reduce
Array.prototype.uniq = function() {
let result = this.reduce((pre, cur) => {
if (pre.includes(cur)) {
return pre
} else {
return pre.concat(cur)
}
}, [])
return result
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
方法 2: 通过 Map 对象保存键值对。任何值都可以作为一盒键或者一个值。
Array.prototype.uniq = function() {
const res = new Map()
return this.filter((el) => !res.has(el) && res.set(el, true))
}
1
2
3
4
2
3
4