JS實現(xiàn)數(shù)組去重方法總結(jié)

話不多說,我們這就進入正文。
第一種:使用forEach從傳入?yún)?shù)的下一個索引值開始尋找是否存在重復(fù),如果不存在重復(fù)則push到新的數(shù)組,達到去重的目的。

noRepeat = (repeatArray) => {
    var result = [];
    repeatArray.forEach((value, index ,arr) => {  
        var isNoRepeat = arr.indexOf(value,index+1);  
        if(isNoRepeat === -1){
            result.push(value);
        }
    })
    return result;
};

還可以換一種方式實現(xiàn),利用新數(shù)組,遍歷要去重的數(shù)組,判斷通過遍歷的數(shù)值是否在新數(shù)組里面存在,如果不存在,則push到新數(shù)組里面。代碼如下:

noRepeat = (repeatArray) => {
    var result = [];
    repeatArray.forEach((value, index ,arr) => {
        if (result.indexOf(value) === -1 ) {
            result.push(value);
        }
    })
    return result;
};

第二種:利用對象的屬性不能重復(fù)的特點進行去重。

    noRepeat = (repeatArray) => {
        var hash = {};
        var result = [];
        repeatArray.forEach((value, index ,arr) => {
            if (!hash[value]) {
                hash[value] = true;
                result.push(value);
            }
        })
        return result;
    };

第三種:先將數(shù)組進行排序,然后通過對比相鄰的數(shù)組進行去重。

    noRepeat = (repeatArray) => {
        repeatArray.sort();
        var result = [];
        repeatArray.forEach((value, index ,arr) => {
            if (value !== arr[index+1]) {
                result.push(value);
            }
        })
        return result;
    };

第四種:利用ES6的Set新特性(所有元素都是唯一的,沒有重復(fù))。需要注意的是,可能存在兼容性問題。

    noRepeat = (repeatArray) => {
        var result = new Set();
        repeatArray.forEach((value, index ,arr) => {
            result.add(value);
        })
        return result;
    };

該方法處理多個數(shù)組的去重是相當(dāng)?shù)暮糜茫a如下:

let array1 = [1, 2, 3, 4];
let array2 = [2, 3, 4, 5, 6];
let noRepeatArray = new Set([... array1, ... array2]);
console.log('noRepeatArray:', noRepeatArray);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容