数组去重的方法

110 阅读1分钟

1.单个数组的去重

Array.from(new Set(arr))

2.多个数组去重 返回不同数据展示

let a = [1, 2, 3, 4]

let b = [3, 4, 5]

let union = [...new Set([...a, ...b])]

console.log(union)

3.单个数组对象去重

let b = [{ id: '4', result: '第三' }, { id: '2', result: '第四' }, { id: '2', result: '第二' }]

let d = []

let hash = {}

d = b.reduce((item, next) => {

hash[next.id] ? '' : hash[next.id] = true && item.push(next)

return item

}, [])

console.log(d, '看看看')

4.多个数组对象去重  

let jsonArray = [{ id: '1', result: '第一' }, { id: '2', result: '第二' }]

let b = [{ id: '4', result: '第三' }, { id: '3', result: '第四' }, { id: '2', result: '第二' }]

let c = [...jsonArray, ...b] //两个数组合并一个的简单方法

let d = []

let hash = {}

d = c.reduce((item, next) => {

hash[next.id] ? '' : hash[next.id] = true && item.push(next)

return item

}, [])

console.log(d, '看看看')