話不多說(shuō),我們這就進(jìn)入正文。
第一種:使用forEach從傳入?yún)?shù)的下一個(gè)索引值開(kāi)始尋找是否存在重復(fù),如果不存在重復(fù)則push到新的數(shù)組,達(dá)到去重的目的。
noRepeat = (repeatArray) => {
var result = [];
repeatArray.forEach((value, index ,arr) => {
var isNoRepeat = arr.indexOf(value,index+1);
if(isNoRepeat === -1){
result.push(value);
}
})
return result;
};
還可以換一種方式實(shí)現(xiàn),利用新數(shù)組,遍歷要去重的數(shù)組,判斷通過(guò)遍歷的數(shù)值是否在新數(shù)組里面存在,如果不存在,則push到新數(shù)組里面。代碼如下:
noRepeat = (repeatArray) => {
var result = [];
repeatArray.forEach((value, index ,arr) => {
if (result.indexOf(value) === -1 ) {
result.push(value);
}
})
return result;
};
第二種:利用對(duì)象的屬性不能重復(fù)的特點(diǎn)進(jìn)行去重。
noRepeat = (repeatArray) => {
var hash = {};
var result = [];
repeatArray.forEach((value, index ,arr) => {
if (!hash[value]) {
hash[value] = true;
result.push(value);
}
})
return result;
};
第三種:先將數(shù)組進(jìn)行排序,然后通過(guò)對(duì)比相鄰的數(shù)組進(jìn)行去重。
noRepeat = (repeatArray) => {
repeatArray.sort();
var result = [];
repeatArray.forEach((value, index ,arr) => {
if (value !== arr[index+1]) {
result.push(value);
}
})
return result;
};
第四種:利用ES6的Set新特性(所有元素都是唯一的,沒(méi)有重復(fù))。需要注意的是,可能存在兼容性問(wèn)題。
noRepeat = (repeatArray) => {
var result = new Set();
repeatArray.forEach((value, index ,arr) => {
result.add(value);
})
return result;
};
該方法處理多個(gè)數(shù)組的去重是相當(dāng)?shù)暮糜?,代碼如下:
let array1 = [1, 2, 3, 4];
let array2 = [2, 3, 4, 5, 6];
let noRepeatArray = new Set([... array1, ... array2]);
console.log('noRepeatArray:', noRepeatArray);