手写数组去重
注意
实现数组去重
答:
- 使用ES6,工作中常用
const arr = [1, 2, 3, 1, 3, 4, 5, 4]
console.log([...new Set(arr)]) // [1, 2, 3, 4, 5]
1
2
2
- 使用For循环,常见思路
function unique(arr) {
const res = []
for (let index=0, len=arr.length; index<len; index++) {
if (res.indexOf(arr[index]) === -1) {
res.push(arr[index])
}
}
return res
}
// 测试
const arr = [1, 2, 3, 1, 3, 4, 5, 4]
unique(arr) // [1, 2, 3, 4, 5]
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- 上一节复习了reduce, 下面用reduce来实现
function unique(arr) {
return arr.reduce((accumulator, currentVal) => {
if (accumulator.indexOf(currentVal) === -1) accumulator.push(currentVal)
return accumulator
}, [])
}
// 测试
const arr = [1, 2, 3, 1, 3, 4, 5, 4]
unique(arr) // [1, 2, 3, 4, 5]
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
编辑 (opens new window)
上次更新: 2025/07/17, 07:17:44