前端数组去重曾经不是一个陈腐的话题了,对于去重的形式也是有很多姿态,本文介绍几种罕用的去重形式。
- for – of 循环去重
let arr = [1, 2, 3, 3, 4,1]
function unique(arr) {
let tempt = [], obj = {}
for (let item of arr) {
if (!obj[item]) {
obj[item] = item
tempt.push(item)
}
}
return tempt
}
console.log(unique(arr)) // [1, 2, 3, 4]
- ES6两种去重形式
// 形式1
Array.from(new Set(arr))
// 形式2
[...new Set(arr)]
- filter去重
// 该形式对数组循环了两次,不倡议应用
let re = arr.filter((item, index) => {
return arr.indexOf(item) === index
})
- reduce去重
let newArr = arr.reduce((pre,cur)=>{
if(!pre.includes(cur)){
pre.push(cur)
}
return pre
},[])
那么问题来了,==如果指标数组存在雷同的援用类型元素呢?==咱们把arr换成[5, ‘1’, 5, 1, 2, {}, {}, /a/, /a/]
- 那么for-of返回值为
[ 5, '1', 2, {}, /a/ ] // 未辨别string类型的1和number类型的1
- 其余几种形式
[5, '1', 2, {}, {}, /a/, /a/] // 援用类型的元素未能去重(这里看怎么了解,两个值雷同的援用类型不肯定雷同,两者所指向不肯定雷同)
由上可见,仿佛是每种形式都有一些缺点,须要一种欠缺的形式来对这些问题独自解决
- 去重完整版
Array.prototype.unique = function () {
if (this) {
let obj = {}, tempt = []
this.forEach(item => {
// 通过类型 + 值来确定唯一性
if (!obj.hasOwnProperty(typeof item + item)) {
obj[typeof item + item] = item
tempt.push(item)
}
})
return tempt
}
}
let arr = [5, '1', 5, 1, 2, {}, {}, /a/, /a/]
console.log(arr.unique()) // [ 5, '1', 1, 2, {}, /a/ ]
下面的办法只是一种思路,其余法式还有待各位观众姥爷挖掘,如有谬误,欢送大家留言斧正
发表回复