1.双重for循环去重
//方式一 双for循环去重
let arrObj=[
{name:"xiangming",age:18,id:"001"},
{name:"xianglan",age:19,id:"002"},
{name:"xiangzhang",age:18,id:"001"},
{name:"xianghua",age:20,id:"003"},
{name:"xianggao",age:21,id:"003"},
{name:"xiangdu",age:18,id:"001"}
]
for (let i = 0; i < arrObj.length; i++) {
for(let j=i+1;j<arrObj.length;j++){
if(arrObj[i].id==arrObj[j].id){
arrObj.splice(j,1);
j--;
}
}
}
console.log(arrObj);
结果:
2.map方式
//方式一 Map()去重
let arrObj=[
{name:"xiangming",age:18,id:"001"},
{name:"xianglan",age:19,id:"002"},
{name:"xiangzhang",age:18,id:"001"},
{name:"xianghua",age:20,id:"003"},
{name:"xianggao",age:21,id:"003"},
{name:"xiangdu",age:18,id:"001"}
]
let map=new Map();
for (let i = 0; i < arrObj.length; i++) {
if(!map.has(arrObj[i].id)){
map.set(arrObj[i].id);
i--;
}else{
arrObj.splice(i,1)
}
}
console.log(arrObj);
结果:
3.forEach与includes去重
//方式三 forEach与includes去重
let arrObj=[
{name:"xiangming",age:18,id:"001"},
{name:"xianglan",age:19,id:"002"},
{name:"xiangzhang",age:18,id:"001"},
{name:"xianghua",age:20,id:"003"},
{name:"xianggao",age:21,id:"003"},
{name:"xiangdu",age:18,id:"001"}
]
let newArrId=[];
let newArrObj=[];
arrObj.forEach(item=>{
if(!newArrId.includes(item.id)){
newArrId.push(item.id)
newArrObj.push(item)
}
})
console.log(newArrObj);
结果:
4.indexof去重
let arrObj=[
{name:"xiangming",age:18,id:"001"},
{name:"xianglan",age:19,id:"002"},
{name:"xiangzhang",age:18,id:"001"},
{name:"xianghua",age:20,id:"003"},
{name:"xianggao",age:21,id:"003"},
{name:"xiangdu",age:18,id:"001"}
]
//方式4.1
let newArrId1=[];
let newArrObj1=[];
for (let i = 0; i < arrObj.length; i++) {
if(newArrId1.indexOf(arrObj[i].id)==-1){
newArrId1.push(arrObj[i].id)
newArrObj1.push(arrObj[i])
}else{
arrObj.splice(i,1)
i--;
}
}
console.log(newArrObj1,'方式1');
//方式4.2
let newArrId2=[];
let newArrObj2=[];
for (let i = 0; i < arrObj.length; i++) {
if(newArrId2.indexOf(arrObj[i].id)==-1){
newArrId2.push(arrObj[i].id)
newArrObj2.push(arrObj[i])
}else{
arrObj.splice(i,1)
i--;
}
}
console.log(newArrObj2,'方式2');
结果:
5.对象访问属性的方法
//方式五 对象属性方式
let arrObj=[
{name:"xiangming",age:18,id:"001"},
{name:"xianglan",age:19,id:"002"},
{name:"xiangzhang",age:18,id:"001"},
{name:"xianghua",age:20,id:"003"},
{name:"xianggao",age:21,id:"003"},
{name:"xiangdu",age:18,id:"001"}
]
let newArr=[]
let obj={}
//方式5.1
for (let i= 0; i< arrObj.length; i++) {
if(!obj[arrObj[i].id]){
obj[arrObj[i].id]=true
newArr.push(arrObj[i])
}
}
console.log(newArr);
//方式5.2
for (let i= 0; i< arrObj.length; i++) {
if(!obj[arrObj[i].id]){
obj[arrObj[i].id]=true
}else{
arrObj.splice(i,1);
i--;
}
}
console.log(arrObj);
结果: