js中数组对象去重

1
2
3
4
5
6
7
8
9
10
11
const arr = [
{ id: 1, parentid: 0 },
{ id: 2, parentid: 1 },
{ id: 3, parentid: 1 },
{ id: 3, parentid: 1 },
{ id: 4, parentid: 2 },
{ id: 5, parentid: 2 },
{ id: 6, parentid: 0 },
{ id: 6, parentid: 0 },
{ id: 7, parentid: 0 },
]

数组对象去重方法一

1
2
3
4
5
6
7
8
9
let obj1 = {}
let res1 = []
arr.forEach(item => {
if (!obj1[item.id]) {
res1.push(item)
obj1[item.id] = true
}
})
console.log(res1)

数组对象去重方法二

1
2
3
4
5
6
7
let obj2 = {}
let res2 = []
res2 = arr.reduce((prev, item) => {
obj2[item.id] ? '' : (obj2[item.id] = true && prev.push(item))
return prev
}, [])
console.log(res2)

reduce的用法:

reduce()方法接收一个函数作为累加器,reduce为数组中每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,回调函数接收的四个参数:初始值(上一次回调的返回值)、当前元素、当前索引、原数组。

语法:arr.reduce(callback, [initialValue])

callback中的 4 个参数:

  1. previousValue:上一次调用回调返回的值,或者是提供的初始值initialValue
  2. currentValue:数组中当前被处理的元素
  3. index:当前元素在数组中的索引
  4. array:调用的数组

initialValue:作为第一次调用callback的第一个参数