数组去重
ES6 set
function dedupe(array){
return Array.from(new Set(array));
}
dedupe([1,1,2,3]) //[1,2,3]
let arr = [1,2,3,3];
let resultarr = [...new Set(arr)];
console.log(resultarr); //[1,2,3]
不能用于包含对象的数组去重,因为对象是不会完全相等的
indexOf
dedupe (array) {
let arr = []
array.forEach((item) => {
(JSON.stringify(arr).indexOf(JSON.stringify(item)) === -1) && arr.push(item)
})
return arr
}
includes
dedupe (array) {
let arr = []
array.forEach((item) => {
(!JSON.stringify(arr).includes(JSON.stringify(item))) && arr.push(item)
})
return arr
}
includes
在IE下不兼容
reduce
unique (arr) {
var ret = []
arr.reduce(function (prev, next) {
prev[next] = (prev[next] + 1) || 1
if (prev[next] === 1) ret.push(next)
return prev
},
{})
return ret
}
实战
function getType (item) {
let type = Object.prototype.toString.call(item)
let regex = /\[object\s(\w+)\]/ // 定义正则
let types = type.replace(regex, function (str, p1) { // replace正则匹配
return p1.toLocaleLowerCase()
})
return types
}
function resetArray (arr) {
let str = Array.from(new Set(arr))
let bts = []
str.forEach((item) => {
let type = getType(item)
if (type !== 'object' && type !== 'array') {
bts.push(item)
} else {
if (JSON.stringify(bts).indexOf(JSON.stringify(item)) === -1) bts.push(item)
}
})
return bts
}
这个方法会将NaN去重