例如:想去除重复id为1的项

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(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(find);
}

 

方法三

通过reduce方法,通过定义的obj,判断obj[next.id] 是否存在,存在设置为“”,不存在则push

reduce() {
let obj = {};
let reduce = [];
reduce = this.arr.reduce(function(item, next) {
//item为没有重复id的数组,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(forData);
}

    let obj = {};
    var reduce = this.persons.reduce((curr, next) => {
      /*判断对象中是否已经有该属性  没有的话 push 到 curr数组*/
      obj[next.age + next.name] ? '' : obj[next.age + next.name] = curr.push(next);
      return curr;
    }, []);

    console.log('reduce', reduce);
posted on   桃子-s  阅读(880)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示