溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

javascript數(shù)組去重方法有哪些

發(fā)布時間:2021-08-07 10:54:58 來源:億速云 閱讀:117 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關(guān)javascript數(shù)組去重方法有哪些的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

 第一種--對象鍵值去重

Array.prototype.unique1 = function () {
   var r = {},
    temp = []
   for (var i = 0; i < this.length; i++) {
    if (!r[this[i]]) {
     r[this[i]] = 1
     temp.push(this[i])
    }
   }
   return temp
  }

第二種--splice刪除去重

Array.prototype.unique2 = function () {
   for (var i = 0; i < this.length; i++) {
    for (var j = i + 1; j < this.length; j++) {
     if (this[i] === this[j]) {
      this.splice(j, 1)
      j--
     }
    }
   }
   return this
  }

第三種--利用數(shù)組indexOf方法

// 循環(huán)遍歷當(dāng)前數(shù)組,當(dāng)前不在臨時數(shù)組的,push
  Array.prototype.unique3 = function () {
   var temp = []
   for (var i = 0; i < this.length; i++) {
    if (temp.indexOf(this[i]) === -1) temp.push(this[i])
   }
   return temp
  }

第四種--數(shù)組下標(biāo)

// 當(dāng)前數(shù)組的第i項在當(dāng)前數(shù)組第一次出現(xiàn)的位置不是i,當(dāng)前項即重復(fù),反之
  Array.prototype.unique4 = function () {
   var temp = [this[0]]
   for (var i = 1; i < this.length; i++) {
    if (this.indexOf(this[i]) === i) temp.push(this[i])
   }
   return temp
  }

第五種

// 先排序,找相鄰的項
  // 這個會改變原來數(shù)組的順序
  Array.prototype.unique5 = function () {
   var tempArr = this.sort(),
    temp = [tempArr[0]]
   for (var i = 1; i < tempArr.length; i++) {
    if (tempArr[i] !== temp[temp.length - 1]) temp.push(tempArr[i])
   }
   return temp
  }

第六種

// 優(yōu)化遍歷數(shù)組
  // 獲取沒重復(fù)的最右一值放入新數(shù)組
  Array.prototype.unique6 = function () {
   var temp = []
   for (var i = 0; i < this.length; i++) {
    for (j = i + 1; j < this.length; j++) {
     if (this[i] === this[j]) {
      i++;
      j = i;
     }
    }
    temp.push(this[i])
   }
   return temp
  }

第七種--es6 set

  Array.prototype.unique7 = function () {
   var temp = new Set(this)
   return [...temp]
  }

第八種--filter

  Array.prototype.unique8 = function () {
   return this.filter(function (ele, index, self) {
    return self.indexOf(ele) === index;
   })
  }

感謝各位的閱讀!關(guān)于“javascript數(shù)組去重方法有哪些”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI