往常在对数组中的对象去重如:
let person = [
{ id : 1,text:1},
{ id : 2,text:2},
{ id : 3,text:3},
{ id : 1,text:4}
]
要想将 id 重叠的 数据去重,我们通常会采用复杂的对数组循环判断的方式,但是在ES5出现reduce之后,我们可以采用reduce来对数组中的对象去重。
在 Array.prototype.reduce 方法中,可以传递四个参数:
previousValue : 初始值或上一次 回调函数的返回值;
currentValue : 本次循环(回调)将要执行的值;
index : "currentValue " 的索引值;
arr : 数组本身
在使用reduce对数组去重一般只需要用到 previousValue 和 currentValue ;
实现过程如下:
let person = [
{ id:1 , text: 3},
{ id:2 , text: 4},
{ id:5 , text: 3},
{ id:1 , text: 2}
];
let obj = {};
person = person.reduce( ( pre,cur ) => {
obj[cur.id] ? "" : obj[cur.id] = true && pre.push(cur);
return pre;
},[]);
console.log(person);
输出结果如下:
当然,也有可能需求是将 id 相同的部分的 text 组合成一个数组,实现过程如下:
let person = [
{ id:1 , text: 3},
{ id:2 , text: 4},
{ id:5 , text: 3},
{ id:1 , text: 2},
{ id:2 , text: 5},
{ id:2 , text: 6}
];
let obj = {};
person = person.reduce( ( pre,cur ) => {
if(obj[cur.id]){
pre.map(
item => item.id === cur.id ? item.text = Array.prototype.concat(item.text,cur.text): ''
);
}else {
obj[cur.id] = true && pre.push(cur);
}
return pre;
},[]);
console.log(person);
输出结果如下: