1.reduce 结合 includes
let array = [1,2,3,4,21,2,333,12,33,44,55,1,2,3,4,5]
let arry2 = array.reduce(function(pre,cut){
if(!pre.includes(cut)){
pre.push(cut)
}
return pre
},[])
conso0le.log(arry2)
2.for循环splice 删除重复元素
let array = [1,2,3,4,21,2,333,12,33,44,55,1,2,3,4,5]
for(let i=0;i
for(let j = i+1;j
if(array[i] == array[j]){
array.splice(j,1)
j--
}
}
}
console.log(array)
3. forEach 结合 includes indexOf
let array = [1,2,3,4,21,2,333,12,33,44,55,1,2,3,4,5]
let newArr = []
array.forEach(function(cut,index) {
// if(newArr.indexOf(cut)==-1) {
// newArr.push(cut)
// }
//同理可以用 includes
if(!newArr.includes(cut)) {
newArr.push(cut)
}
})
console.log(newArr)
4. filter 结合indexOf
let array = [1,2,3,4,21,2,333,12,33,44,55,1,2,3,4,5]
let array2 = array.filter(function(item,index) {
return array.indexOf(item) === index
})
console.log(array2)
5.ES6 set
Array,from(new Set(arr))
或者简化为[...new Set(arr)]
6 ES6 map
let array = [1,2,3,4,21,2,333,12,33,44,55,1,2,3,4,5]
let newArr = []
let map = new Map()
array.forEach(function(item,index){
if(map.has(item)) {
map.set(item,true)
}else{
map.set(item,false)
newArr.push(item)
}
})
console.log(newArr)