基础类型数组去重
const arr = [1, 1, 2, 3, 3, 4, 5]
ES5
function unique(arr) {
return arr.filter((item, index, array) => array.indexOf(item) === index)
}
ES6
function unique (arr) {
const seen = new Map()
return arr.filter((a) => !seen.has(a) && seen.set(a, 1))
}
// or
function unique(array) {
return [...new Set(array)]
}
复杂类型数组去重
const array = [{value: 1}, {value: 1}, {value: 2}]
ES5
function unique(arr) {
var obj = {}
return arr.filter((item, index, array) => !obj.hasOwnProperty(JSON.stringify(item)) && (obj[JSON.stringify(item)] = true))
}
ES6
function unique (arr) {
const seen = new Map()
return arr.filter((a) => !seen.has(JSON.stringify(a)) && seen.set(JSON.stringify(a), 1))
}