數組去重方法

數組去重方法

常規方法

思路數組

  1. 構建一個新的數組用來存放結果
  2. for循環中每次從原數組取出一個元素,用這個元素循環與結果數組對比
  3. 若結果數組中沒有該元素,則存到結果數組中
  1. Array.prototype.unique = 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 = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'];
    console.log(arr.unique())

比上述的方法高效一點

思路微信

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

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

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

  1. Array.prototype.unique = 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 = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'];
    console.log(arr.unique())

這種方法會在去重以前進行排序,因此最後返回的結果也是排序以後的。若是要求不改變數組的順序去重,這種方法是不可取的。code

3、利用哈希值

思路對象

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

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

  1. Array.prototype.unique = function() {
        var res = [this[0]],
            obj = {};
    
        for (var i = 1; i < this.length; i++) {
            if (!obj[this[i]]) {
                res.push(this[i]);
                obj[this[i]] = 1;
            }
        }
        return res;
    }
    
    var arr = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'];
    console.log(arr.unique())

這種方法效率最高,在處理長數組的時候頗有優點,推薦使用。排序

感興趣的能夠掃碼關注微信公衆號:io

 

你還有什麼好的方法,能夠告訴我,謝謝~~

相關文章
相關標籤/搜索