const p = [{id:1, name: 'ss'},
{id:1, name: 'ssa'},
{id:2, name: 'a'},
{id:3, name: 'saas'},
{id:4, name: 'sw2121s'},
{id:4, name: 'ssllll'},
{id:4, name: 'ssppp'}];
const filterArray = (arr, id) =>{
const have = {};
return arr.reduce((item, next)=> { // 使用累加器,将得到的数据push到空数组
// have[next[id]] ? '' : have[next[id]] = true && item.push(next); // esline会校验不通过,原因:eslint判断have[next[id]]定义了但是没有赋值
have[next[id]] = have[next[id]] ? undefined : true && item.push(next) // 判断have对象里面是否存在相同的id,如果不存在,将next赋值给id,并且push到初始数据中
return item;
}, []); // 定义初始数据
}
// 改写
const filterArray = (arr, id) => {
var have = {};
return arr.reduce((item, next) =>{
if(!have[next[id]]){
have[next[id]] = true && item.push(next)
}
return item;
}, []);
}
数组去重 - 元素为对象
于 2022-06-14 16:53:19 首次发布