1 indexOf + filter
const array = [6,7,3,3,4,5,2,3]
function unique (array) {
return array.filter ((item,index)=>{
return array.indexOf(item) === index
})
}
console.log(unique(array))
2 相邻元素排序
function unique (array) {
array = array.sort()
let res = []
for(i=0;i<array.length;i++) {
if(array[i] !== array[i+1]){
res.push(array[i])
}
}
return res
}
console.log(unique(array))
3 set 结构赋值
function unique (array) {
return [...new Set(array)]
}
console.log(unique(array))
4 先排序,在双指针
function unique (array) {
array = array.sort()
let left = 0
let right = 1
while(right <array.length) {
if(array[left] === array[right]) {
right++
}else {
array[left+1] = array[right]
left++
right++
}
}
return array.slice(0,left+1)
}
console.log(unique(array))