三种方式实现对数组对象的去重。
一、reduce
const resource = [{
name: '张三',
age: 20,
id: 001
},
{
name: '李四',
age: 20,
id: 001
},
{
name: '王二麻子',
age: 20,
id: 001
},
{
name: '张三',
age: 20,
id: 001
},
]
const unique1 = (arr, key) => {
let item = arr[0]
return arr.reduce((prev, next) => {
if (item[key] !== next[key]) {
prev.push(next)
item = next
}
return prev
}, [])
}
console.log(unique1(resource, 'name'))
二、for循环
const unique2 = (arr, key) => {
let item = arr[0]
let newArr = []
for (let i = 0; i < arr.length; i++) {
if (item[key] !== arr[i][key]) {
newArr.push(arr[i])
item = arr[i]
}
}
return newArr
}
console.log(unique2(resource, 'name'))
三、Map去重
const unique3 = (arr, key) => {
const m = new Map()
for (const item of arr) {
if(!m.has(item[key])) {
m.set(item[key], item)
}
}
return [...m.values()]
}
console.log(unique3(resource, 'name'))
三种方式,大同小异,也不难理解,希望对你有帮助。