数组去重

2019-10-08  本文已影响0人  陈大事_code

分类

  1. 非对象数组去重
  2. 对象数组去重

分类一 --- 非对象数组去重

方法一: 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'}]
上一篇下一篇

猜你喜欢

热点阅读