1,建個新數組,遍歷老數組,若在新數組裏沒找到,則將這個元素放到新數組,而後返回javascript
Array.prototype.unique1 = function() { var n = []; for(var i = 0; i < this.length; i++) { if (n.indexOf(this[i]) == -1) n.push(this[i]); } return n; }
2,利用hash表,將放到新數組的元素在hash表中存true值,下次遍歷數組時檢查元素在hash表中的值html
Array.prototype.unique2 = function() { var n = {},r=[]; for(var i = 0; i < this.length; i++) { if (!n[this[i]]) { n[this[i]] = true; r.push(this[i]); } } return r; }
3,遍歷老數組,如果這個第i項的元素的位置不是第i項,則是重複的,忽略掉java
Array.prototype.unique3 = function() { var n = [this[0]]; for(var i = 1; i < this.length; i++) { if (this.indexOf(this[i]) == i) n.push(this[i]); } return n; }
4,先將老數組排序,將老數組第一個放進新數組,老數組第二個與新數組第一個比較,若不同則放進新數組中,若同樣則是重複的,這種打亂原來的順序了數組
Array.prototype.unique4 = function() { this.sort(); var re=[this[0]]; for(var i = 1; i < this.length; i++) { if( this[i] !== re[re.length-1]) { re.push(this[i]); } } return re; }
5,新建一個將原數組排過序的新數組,對新數組進行排序,對應找到重複的元素位置,在原數組裏刪掉它函數
Array.prototype.unique5 = function(){ var self = this; var _a = this.concat().sort(); _a.sort(function(a,b){ if(a == b){ var n = self.indexOf(a); self.splice(n,1); } }); return self; };
6,先把reduce方法分析下,arr.reduce(callback,[initialValue]) callback函數有4個參數,第一個參數previousValue,如果有初始值initialValue,則是初始值,若沒有,則是數組中的第一個值,第二個currentValue是數組中當前被處理的元素,在新建數組中遍歷老數組中的每一個元素,如果沒有,在新數組中加上測試
Array.prototype.unique6 = function() { return this.reduce(function(p, c) { if (p.indexOf(c) < 0) p.push(c); return p; }, []); };
一個10000個隨機數的數組的六種測試用時:this
method 1 used 349msspa
method 2 used 5msprototype
method 3 used 442mscode
method 4 used 15ms
method 5 used 13ms
method 6 used 424ms