对于[15,25,35,17,45,95,25,95,95,1]这种类型的去重
- 使用indexof去重
let mapList1 = [15,25,35,17,45,95,25,95,95,1]
let mapList2 = []
for(let i=0;i<mapList1.length;i++){
if(mapList2.indexOf(mapList1[i]) == '-1'){
mapList2.push(mapList1[i])
}
}
- 使用array.from()和set()
let mapList1 = [15,25,35,17,45,95,25,95,95,1]
let mapList2 = []
mapList2 = Array.from(new Set(mapList1))
- 使用 …拓展运算符
mapList2 = [...new Set(mapList1)]
对于对象数组的去重
let mapList1=[
{ id:1, name: '西门吹雪'},
{ id:2, name: '叶孤城'},
{ id:1, name: '陆小凤'},
{ id:3, name: '老刀把子'},
{ id:4, name: '西门吹雪'},
{ id:5, name: '陆小凤'}
]
let array = {}, List=[]
for(let i=0;i<objectArray.length;i++){
let item = objectArray[i]
if(!array[item['id']]){ // 判断是否存在该id 也可以使用name
array[item['id']] = List.push(item)
}
}
console.log(List)
还有一种reduce方式对对象数组查重
let obj = {};
mapList1.reduce((item,next) => {
obj[next.id] ? "" : obj[next.id] = true && item.push(next);
return item ;
},[]) //
暂时对reduce方法还在理解中,先把方法放上