數(shù)組去重是日常工作經(jīng)常出現(xiàn)的場(chǎng)景,解決辦法有多種,簡(jiǎn)潔的、詳細(xì)的等等,舉例我用到過的方法
利用數(shù)組對(duì)象的唯一性
object.hasOwnProperty(prop),返回一個(gè)布爾值,對(duì)象自身中是否有該屬性,忽略從原型鏈上繼承的屬性,兼容性強(qiáng)
// 數(shù)組去重
const array = [{ value: 1 }, { value: '1' }, { value: 2 }, '1', 1, 1]
const notReapeatedArray = []
let notReapeatedObj = {}
for (let index = 0; index < array.length; index++) {
const prop = array[index];
// 去除JS強(qiáng)制類型轉(zhuǎn)換的干擾,比如1、"1"是不相等的
const rely = prop + JSON.stringify(prop)
// hasOwnProperty不會(huì)遍歷原型鏈上的屬性
if (!notReapeatedObj.hasOwnProperty(rely)) {
notReapeatedObj[rely] = true
notReapeatedArray.push(prop)
}
}
// [ { value: 1 }, { value: '1' }, { value: 2 }, '1', 1 ]
console.log(notReapeatedArray);
兩次for循環(huán)
// 數(shù)組去重
const array = ['1', 1, '1', ['15'], 15]
// 沒有重復(fù)項(xiàng)的數(shù)組,待push
const notReapeatedArray = []
for (i = 0; i < array.length; i++) {
// 遍歷數(shù)組的每一項(xiàng),是否在notReapeatedArray中出現(xiàn)過,若是,跳出循環(huán),否則放到notReapeatedArray里
for (j = 0; j < notReapeatedArray.length; j++) {
if (array[i] === notReapeatedArray[j]) {
// 有相同項(xiàng)出現(xiàn)了,直接跳出循環(huán),說明array[i]已經(jīng)存在了
break
}
}
// array[i] 在數(shù)組notReapeatedArray中循環(huán)后未出現(xiàn)過,j肯定是notReapeatedArray的長度,因?yàn)槊恳豁?xiàng)都被循環(huán)了
if (j == notReapeatedArray.length) {
notReapeatedArray.push(array[i])
}
}
console.log(notReapeatedArray);//[ '1', 1, [ '15' ], 15 ]
filter遍歷,結(jié)合indexOf,兼容ie9及以上
filter返回一個(gè)新數(shù)組,其中包含所有符合過濾規(guī)則的元素,兼容ie9及以上,兼容舊環(huán)境,polyfill,點(diǎn)我
indexOf()方法返回在數(shù)組中可以找到一個(gè)給定元素的第一個(gè)索引,如果不存在,則返回-1,兼容ie9及以上;兼容舊環(huán)境,polyfill,點(diǎn)我
把polyfill加到代碼中即可
// 使用filter方便判斷當(dāng)前項(xiàng)是否和上一項(xiàng)相同
const array = ['1', 1, '1', ['15'], 15]
const notReapeatedArray = array.filter((item, index) => {
return array.indexOf(item) === index
})
console.log(notReapeatedArray);//[ '1', 1, [ '15' ], 15 ]
ES6 Set對(duì)象
Set中的元素只會(huì)出現(xiàn)一次,即Set中的元素是唯一的
ES6的兼容性經(jīng)過babel處理就行啦
const array = ['1', 1, '1', ['15'], 15]
const notReapeatedArray = new Set(array)
//返回一個(gè)Set對(duì)象,Set { '1', 1, [ '15' ], 15 }
console.log(notReapeatedArray);
//用Array.from 轉(zhuǎn)成Array
Array.from(notReapeatedArray)//[ '1', 1, [ '15' ], 15 ]
// 用...操作符把Set轉(zhuǎn)換成Array
console.log([...notReapeatedArray]);//[ '1', 1, [ '15' ], 15 ]