這篇文章給大家分享的是有關javascript數組去重方法有哪些的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
第一種--對象鍵值去重
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
}第三種--利用數組indexOf方法
// 循環遍歷當前數組,當前不在臨時數組的,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
}第四種--數組下標
// 當前數組的第i項在當前數組第一次出現的位置不是i,當前項即重復,反之
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
}第五種
// 先排序,找相鄰的項
// 這個會改變原來數組的順序
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
}第六種
// 優化遍歷數組
// 獲取沒重復的最右一值放入新數組
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;
})
}感謝各位的閱讀!關于“javascript數組去重方法有哪些”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。