arr = [
{ id: 1, name: '张一', age: 20 },
{ id: 1, name: '张一', age: 20 },
{ id: 2, name: '张二', age: 20 },
{ id: 3, name: '张三', age: 20 },
];
方法一
通过forEach再通过some方法判断数组是否包含当前对象id,不包含则添加
some() {
let some: any = [];
this.arr.forEach(el => {
if (!some.some(e => e.id == el.id)) {
some.push(el);
}
});
console.log('%c [ some去重结果 ]-43', 'font-size:13px; background:pink; color:#bf2c9f;', some);
}
方法二
通过forEach再通过find方法判断数组是否包含当前对象id,不包含则添加
find() {
let find: any = [];
this.arr.forEach(el => {
if (!find.find(e => e.id == el.id)) {
find.push(el);
}
});
console.log('%c [ find去重 ]-51', 'font-size:13px; background:pink; color:#bf2c9f;', find);
}
方法三
通过reduce方法,通过定义的obj,判断obj[next.id] 是否存在,存在设置为“”,不存在则push
reduce() {
let obj = {};
let reduce = [];
reduce = this.arr.reduce(function(item, next) {
obj[next.id] ? '' : (obj[next.id] = true && item.push(next));
return item;
}, []);
console.log(reduce);
}
方法四
通过for循环遍历,再通过some方法判断数组是否包含当前对象id,不包含则添加
forAway() {
let forData = [];
for (let i = 0; i < this.arr.length; i++) {
if (!forData.some(e => e.id == this.arr[i].id)) forData.push(this.arr[i]);
}
console.log('%c [ forData ]-74', 'font-size:13px; background:pink; color:#bf2c9f;', forData);
}
|