let arr = [
{
name:'gwj',
age:28
},
{
name:'lixian',
age:33
},
{
name:'lixian',
age:30
},
{
name:'zhaoliying',
age:35
},
{
name:'gwj',
age:28
}
]
//1.将第一个对象保留
//findIndex返回符合条件的数组的第一个元素索引
let newArr = arr.filter((item,index)=> arr.findIndex(item1 =>
item1.name === item.name) === index)
//newArr
//[{name:'gwj',age:28},{name:'lixian',age:33},{name:'zhaoliying',age:35}]
let newArr1 = arr.filter((item,index)=>arr.findIndex(item1 =>
item1.name === item.name && item.age === item1.age) === index)
//newArr1
//[{name:'gwj',age:28},{name:'lixian',age:33},{name:'lixian',age:30},{name:'zhaoliying',age:35}]
//2.从唯一数组中排除重复项
//find返回符合条件的数组的第一个元素的值(与findIndex类似)
let newArr2 = []
for(let item of arr){
let isExist = newArr2.find(obj => obj.name === item.name)
if(!isExist){
newArr2.push(item)
}
}
//newArr2
//[{name:'gwj',age:28},{name:'lixian',age:33},{name:'zhaoliying',age:35}]
console