javascript數(shù)組去重方法總結(jié)(推薦)
更新時間:2019年03月20日 16:23:23 作者:風語1201
這篇文章主要介紹了javascript數(shù)組去重方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
第一種--對象鍵值去重
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)遍歷當前數(shù)組,當前不在臨時數(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ù)組下標
// 當前數(shù)組的第i項在當前數(shù)組第一次出現(xiàn)的位置不是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 }
第五種
// 先排序,找相鄰的項 // 這個會改變原來數(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ù)組 // 獲取沒重復的最右一值放入新數(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; }) }
以上所述是小編給大家介紹的javascript數(shù)組去重方法詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
JavaScript中把數(shù)字轉(zhuǎn)換為字符串的程序代碼
本篇文章是對JavaScript中把數(shù)字轉(zhuǎn)換為字符串的實現(xiàn)代碼進行了詳細的分析介紹,需要的朋友參考下2013-06-06Javascript中indexOf()和lastIndexOf應用方法實例
這篇文章主要介紹了JavaScript中的indexOf()和lastIndexOf()方法使用實例,是JS入門學習中的基礎知識,有需要的朋友可以參考下。2016-08-08JavaScript ES6中的簡寫語法總結(jié)與使用技巧
我們在看編寫的JS ES6代碼時經(jīng)常會看到許多簡寫的語法,本篇文章就為大家一一介紹JavaScript ES6可以簡寫的語法2018-12-12關(guān)于js的三種使用方式(行內(nèi)js、內(nèi)部js、外部js)的程序代碼
本文主要和大家介紹關(guān)于js的三種使用方式(行內(nèi)js、內(nèi)部js、外部js)的實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家2018-05-05