js去除数组对象中的重复对象
原链接:https://blog.csdn.net/nnaay_/article/details/104689400
1、根据数组对象中的id作比较,id相同的去掉。这种方法只会保留 id 第一个出现的数组
第一种:
var arr = [ {id: 1, name: 'sli', year: 2012}, {id: 2, name: 'ap', year: 2015}, {id: 1, name: 'alslion', year: 2012}, {id: 3, name: 'pose', year: 2012}, ] //删除arr中的重复对象 var newArr= []; var arrId = []; for(var item of arr){ if(arrId.indexOf(item['id']) == -1){ arrId.push(item['id']); newArr.push(item); } } console.log(arrId,newArr);
结果如下:
第二种:reduce()
var arr = [ {name:'uzi',color:'blue'}, {name:'pdd',color:'white'}, {name:'mlxg',color:'orange'}, {name:'uzi',color:'red'}, ] let hash = {}; var newArr = arr.reduce((item, next) => { hash[next.name] ? '' : hash[next.name] = true && item.push(next); return item }, []); console.log(newArr);
结果如下:
第三种:
let arr = [ {name:'黎明',id:21111}, {name:'王小二',id:1111}, {name:'大小二',id:3222} ] arr.splice(arr.findIndex(item => item.id === 3222), 1);
结果如下: