分类
- 非对象数组去重
- 对象数组去重
分类一 --- 非对象数组去重
方法一: set(es6常用)
let arr = [2,3,4,5,5]
let newArr = [...new Set(arr)] // [2,3,4,5]
方法二:reduce
let arr = [2,3,4,4]
let newArr = arr.reduce((prev, item) => {
!prev.includes(item) && prev.push(item) // 若prev中不存在当前item,则push
return prev
}, []) // [2,3,4]
方法三:对象key的唯一性
let arr = [2,3,3,4]
let obj = {}
arr.forEach(item => {
obj[item] = item
})
let newArr = Object.vlaues(obj) // [2,3,4]
分类二 --- 对象数组去重
方法一:对象key的唯一性
let arr = [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 1, name: 'a'}]
let obj = {}
let newArr = []
arr.forEach(item => {
if(!obj[item.id]) {
newArr.push(item)
obj[item.id] = true
}
}) // [{id: 1, name: 'a'}, {id: 2, name: 'b'}]
方法二:reduce
let arr = [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 1, name: 'a'}]
let obj = {}
arr.reduce((prev, cur) => {
obj[cur.id] ? '' : obj[cur.id] = true && prev.push(cur)
return prev
}, []) // [{id: 1, name: 'a'}, {id: 2, name: 'b'}]
网友评论