数组去重
... 2022-11-17 Less than 1 minute
# 数组去重
# 数组单元素去重
const arr = [1,2,3,4,5,6,6,6]
const arrayUnique = [...new Set(arr)]
1
2
3
4
2
3
4
# 数组里面有对象去重
const arr = [{id: 2}, {id: 2}, {id: 3}, {id: 3}, {id:3}]
function arrayUnique(arr, keyName) {
let hash = {}
return arr.reduce((pre, cur) => {
hash[cur[keyName]] ? "" : (hash[cur[keyName]] = true && pre.push(cur))
return pre
}, [])
}
const arrayUnique = arrayUnique(arr, 'id')
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12