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<array.length;i++){
for(let j = i+1;j<array.length;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)
js数组去重
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...