1劝枣、ES6簡單數(shù)組去重
const arr = [1,1,2,3,4,5,6,6,6]
const newArr = Array.from(new Set(arr)) // [1,2,3,4,5,6]
const newArr = [...new Set(arr)] // [1,2,3,4,5,6]
2硝岗、reduce去重
const arr = [1,1,2,3,4,5,6,6,6]
const newArr = arr.reduce((pre, cur) => {
if(!pre.includes(cur)){
pre.push(cur)
}
return pre
}, [])
console.log(newArr) // [1, 2, 3, 4, 5, 6]
3、for循環(huán)去重
const arr = [1,1,2,3,4,5,6,6,6]
let newArr = []
for(let item of arr){
if(newArr.indexOf(item) == -1){
newArr.push(item)
}
}
console.log(newArr) // [1, 2, 3, 4, 5, 6]
4葛圃、sort + for循環(huán)去重
const arr = [1,1,2,3,4,5,6,6,6]
arr.sort()
let newArr = [arr[0]]
for(let i = 1; i < arr.length; i++){
if(arr[i] !== arr[i-1]){
newArr.push(arr[i])
}
}
console.log(newArr) // [1, 2, 3, 4, 5, 6]
其他利用for循環(huán)去重的換個思路就可以了
5、filter去重
const arr = [1,1,2,3,4,5,6,6,6]
const newArr = arr.filter((item, index, arr) => {
return arr.indexOf(item) === index
})
console.log(newArr) // [1, 2, 3, 4, 5, 6]