數(shù)組去重是日常工作經(jīng)常出現(xiàn)的場(chǎng)景,解決辦法有多種官卡,簡(jiǎn)潔的刻坊、詳細(xì)的等等泣侮,舉例我用到過(guò)的方法
利用數(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]
// 沒(méi)有重復(fù)項(xiàng)的數(shù)組蛹锰,待push
const notReapeatedArray = []
for (i = 0; i < array.length; i++) {
// 遍歷數(shù)組的每一項(xiàng)深胳,是否在notReapeatedArray中出現(xiàn)過(guò),若是铜犬,跳出循環(huán)舞终,否則放到notReapeatedArray里
for (j = 0; j < notReapeatedArray.length; j++) {
if (array[i] === notReapeatedArray[j]) {
// 有相同項(xiàng)出現(xiàn)了,直接跳出循環(huán)癣猾,說(shuō)明array[i]已經(jīng)存在了
break
}
}
// array[i] 在數(shù)組notReapeatedArray中循環(huán)后未出現(xiàn)過(guò)敛劝,j肯定是notReapeatedArray的長(zhǎng)度,因?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ò)濾規(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)過(guò)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 ]