Set 方式去重
let array = [1, 2, 3, 4, 5, 6, 6, 7]
console.log(array)
let unique = (array) => [...new Set(array)]
console.log(unique(array))
Map 方式去重
let arr = [1, 2, 3, 3, 4, 5, 2, 5]
console.log(arr)
let uniqueVal = uniqueArr(arr)
console.log(uniqueVal)
function uniqueArr (arr) {
const seen = new Map()
return arr.filter((arr) => !seen.has(arr) && seen.set(arr, 1))
}
键值对 方式去重
let arr = [1, 2, 3, 3, 4, 5, 2, 5]
function uniqueArray (arr) {
let obj = {}
return arr.filter((item, index, arr) => {
return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
})
}
console.log(uniqueArray(arr))
去重引用类型
let arrObj = [{'id': 1, 'name': 'abc'}, {'id': 1, 'name': 'abc'}, {'id': 2, 'name': 'bcd'}, {'id': 3, 'name': 'efg'}]
console.log('arrObj: ', arrObj)
let hash = {}
arrObj = arrObj.reduce((item, next) => {
hash[next.name] ? '' : hash[next.name] = true && item.push(next)
return item
}, [])
console.log(arrObj)