90-js去重对象

1
2
3
4
5
6
7
8
let person = [
{id: 0, name: "小明"},
{id: 1, name: "小张"},
{id: 2, name: "小李"},
{id: 3, name: "小孙"},
{id: 1, name: "小周"},
{id: 2, name: "小陈"},
];

1 向前取值,忽略后面重复的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function fn1(arr){
var obj={}
var re=arr.reduce((cur,next)=>{
if(!obj[next.id]){
obj[next.id]=true
cur.push(next)
}
return cur
},[])

return re
}

console.log(fn1(person));

结果

1
2
3
4
[ { id: 0, name: '小明' },
{ id: 1, name: '小张' },
{ id: 2, name: '小李' },
{ id: 3, name: '小孙' } ]

2 往后取值,忽略前面重复的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function fn2(arr){
var re=[]
for (let i = 0; i < arr.length; i++) {
for(let j=i+1;j<arr.length;j++){
if(arr[i]['id']==arr[j]['id']){
i++
j=i
}
}
re.push(arr[i])
}
return re
}

console.log(fn2(person));

结果:

1
2
3
4
[ { id: 0, name: '小明' },
{ id: 3, name: '小孙' },
{ id: 1, name: '小周' },
{ id: 2, name: '小陈' } ]