介绍几种数组去重的方法
//举例数组:
const arr = [1,1,'2','2',null,null,undefined,undefined,new String('1'),new String('1'),/a/,/a/,NaN,NaN]
set
function uniqueArr (arr) {
return [...new Set(arr)]
}
// [1, "2", null, undefined, String, String, /a/, /a/, NaN]
filter
//indexof只返回匹配的第一个下标
function uniqueArr(arr){
return arr.filter((item,index)=>{
return arr.indexOf(item) === index
})
}
//[1, "2", null, undefined, String, String, /a/, /a/]
reduce
function uniqueArr(arr){
return arr.reduce((pre,cur)=>{
return pre.includes(cur) ? pre : [...pre,cur]
},[])
}
//[1, "2", null, undefined, String, String, /a/, /a/, NaN]
Object键值对
//判断是否有
function uniqueArr(arr){
var obj = {};
return arr.filter((item,index,arr)=>{
return obj.hasOwnProperty(`${typeof item}${item}`) ? false : (obj[`${typeof item}${item}`] = true)
})
}
//[1, "2", null, undefined, String, /a/, NaN]