reduce 对象数组去重:
let person = [
{id: 0, name: "小明"},
{id: 1, name: "小张"},
{id: 2, name: "小李"},
{id: 3, name: "小孙"},
{id: 1, name: "小周"},
{id: 2, name: "小陈"}
];
let obj = {}
person = person.reduce((cur, next) => {
if (!obj[next.id]) {
obj[next.id] = true
cur.push(next)
}
return cur
}, [])
console.log(person)
解析:
其实就是用 obj 来存储已经放入新数组的元素,每次遍历旧数组都去 obj 中检查是否已经存在 id值相同的元素。如果不存在,则放入新数组。
当然,很多人是这么写的:
person = person.reduce((cur, next) => {
obj[next.id] ? '' : obj[next.id] = true && cur.push(next)
return cur
}, [])
其实是一样的