亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

JS實現數組去重方法總結

標簽:
JavaScript

话不多说,我们这就进入正文。
第一种:使用forEach从传入参数的下一个索引值开始寻找是否存在重复,如果不存在重复则push到新的数组,达到去重的目的。

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

还可以换一种方式实现,利用新数组,遍历要去重的数组,判断通过遍历的数值是否在新数组里面存在,如果不存在,则push到新数组里面。代码如下:

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

第二种:利用对象的属性不能重复的特点进行去重。

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

第三种:先将数组进行排序,然后通过对比相邻的数组进行去重。

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

第四种:利用ES6的Set新特性(所有元素都是唯一的,没有重复)。需要注意的是,可能存在兼容性问题。

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

该方法处理多个数组的去重是相当的好用,代码如下:

let array1 = [1, 2, 3, 4];let array2 = [2, 3, 4, 5, 6];let noRepeatArray = new Set([... array1, ... array2]);console.log('noRepeatArray:', noRepeatArray);



作者:甜甜_饭
链接:https://www.jianshu.com/p/85ed71e7ddae


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消