使用set进行简单去重
let arr = [1, 1, 2, 3, 3, 5, 5, 3]
let set = new Set();
arr.forEach(val => {
set.add(val)
})
console.log("arr: ", arr); // 1, 1, 2, 3, 3, 5, 5, 3
console.log("set: ", set); // 1, 2, 3, 5
使用reduce进行复杂数组去重
let person = [
{ id: 0, name: "小明" },
{ id: 1, name: "小张" },
{ id: 2, name: "小李" },
{ id: 3, name: "小孙" },
{ id: 1, name: "小周" },
{ id: 2, name: "小陈" },
];
console.log("过滤前:",person);
let obj = {};
person = person.reduce((cur, next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
}, []) //设置cur默认类型为数组,并且初始值为空的数组
console.log("过滤后:",person);
网友评论