被問到如何給陣列中物件去重,想到set答案肯定錯誤的,這個平時工作中用到的不多,查閱資料,找到給陣列中物件去重的方法,利用物件屬性名的唯一性,怪自己當時沒想到。
方法一:
let ary=[
{id: 0, name: "小明"},
{id: 1, name: "小張"},
{id: 2, name: "小李"},
{id: 3, name: "小孫"},
{id: 1, name: "小周"},
{id: 2, name: "小陳"},
];
var result = [];
var obj = {};
ary.forEach((ele,index)=>{
if(!obj[ele.id]){
result.push(ele);
obj[ele.id]=true;
}
});
//console.log(result)
方法二:用陣列的reduce()方法(累加器)
redeuce()引數:回撥函式,傳遞給函式初始值(可選)
回撥函式的引數:
1:初始值, 或者計算結束後的返回值。
2:當前元素
3:當前元素的索引(可選)
4:當前元素所屬的陣列物件(可選)
let arys=[1,2,3];
//curs第一次為初始值1,之後為上一次累加結果3,
//next當前要累加得元素
var a=arys.reduce((curs,next)=>{
// console.log(next)
//1+2
//3+3
return curs+next;
});
//console.log(a);//6
利用redeuce()為陣列中物件去重
let ary=[
{id: 0, name: "小明"},
{id: 1, name: "小張"},
{id: 2, name: "小李"},
{id: 3, name: "小孫"},
{id: 1, name: "小周"},
{id: 2, name: "小陳"},
];
let obj = {};
ary=ary.reduce((curs,next)=>{
obj[next.id]?"":obj[next.id]=true&& curs.push(next);
return curs;
},[]);