三種經常使用的js數組去重方法

第一種是比較常規的方法

思路:html

1.構建一個新的數組存放結果json

2.for循環中每次從原數組中取出一個元素,用這個元素循環與結果數組對比數組

3.若結果數組中沒有該元素,則存到結果數組中post

Array.prototype.unique1 = function(){
	var res = [this[0]];
	for(var i = 1; i < this.length; i++){
		var repeat = false;
		for(var j = 0; j < res.length; j++){
			if(this[i] == res[j]){
				repeat = true;
				break;
			}
		}
		if(!repeat){
			res.push(this[i]);
		}
	}
	return res;
}
var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
alert(arr.unique1());

第二種方法比上面的方法效率要高

思路:this

1.先將原數組進行排序spa

2.檢查原數組中的第i個元素 與 結果數組中的最後一個元素是否相同,由於已經排序,因此重複元素會在相鄰位置prototype

3.若是不相同,則將該元素存入結果數組中htm

Array.prototype.unique2 = function(){
	this.sort();	//先排序
	var res = [this[0]];
	for(var i = 1; i < this.length; i++){
		if(this[i] !== res[res.length - 1]){
			res.push(this[i]);
		}
	}
	return res;
}
var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
alert(arr.unique2());

第二種方法也會有必定的侷限性,由於在去重前進行了排序,因此最後返回的去重結果也是排序後的。若是要求不改變數組的順序去重,那這種方法便不可取了。對象

第三種方法(推薦使用)

思路:排序

1.建立一個新的數組存放結果

2.建立一個空對象

3.for循環時,每次取出一個元素與對象進行對比,若是這個元素不重複,則把它存放到結果數組中,同時把這個元素的內容做爲對象的一個屬性,並賦值爲1,存入到第2步創建的對象中。

說明:至於如何對比,就是每次從原數組中取出一個元素,而後到對象中去訪問這個屬性,若是能訪問到值,則說明重複。

Array.prototype.unique3 = function(){
	var res = [];
	var json = {};
	for(var i = 0; i < this.length; i++){
		if(!json[this[i]]){
			res.push(this[i]);
			json[this[i]] = 1;
		}
	}
	return res;
}

var arr = [112,112,34,'你好',112,112,34,'你好','str','str1'];
alert(arr.unique3());
 
轉載:http://www.1008a.com/post/277.html
相關文章
相關標籤/搜索