2017-10-10 66 views
0

我已經創建了一個自定義原型,用它來清理一個陣列以便刪除重複項sort它。它的工作,並期待這樣的:用原型修改陣列就地

// given an example array such as this. 
var names = [ 'Lara', 'Lucy', 'Alexa', 'Vanessa', 'Lucy', 'Brianna', 'Sandra' ]; 

Array.prototype.clean_up = function(){ 
    var 
     set = [] 
    ; 
    this.forEach(function(item){ 
     if (set.indexOf(item) === -1) { 
      set.push(item); 
     } 
    }); 

    set.sort(); 

    return set; 
}; 

我唯一的抱怨是,我要這樣稱呼它:

names = names.clean_up(); 

我當然希望我可以把它作爲其次,像Array.sort()(我相信這被稱爲就地實施)。你怎麼能做到這一點?

names.clean_up(); 

編輯:(顯然,這屬於這裏,而不是在Answers)

我目前的解決方案如下所示,但感覺有點無效的。我想知道是否可以做得更好。

Array.prototype.clean_up = function(){ 
    var 
     set = [], 
     self = this 
    ; 
    this.forEach(function(item){ 
     if (set.indexOf(item) === -1) { 
      set.push(item); 
     } 
    }); 

    set.sort(); 

    // reset and re-fill. 
    while (this.length > 0) { 
     this.pop(); 
    } 

    set.forEach(function(item){ 
     self.push(item); 
    }); 
}; 

無效的一個,併爲其他:它已經mentioned幾次,你不應該修改原來的陣列。這是爲什麼?

我的意思是,如果有喜歡的Array.sort()一個函數,那麼就說明,該語言能夠做的,那一些實現似乎是「好」?爲什麼sort()沒問題,但自定義函數不是?

回答

0

如果你想影響陣列的位置,你應該從數組中尋找重複和拼接他們。 Array.prototype.indexOf可與第二個參數一起使用以從當前元素搜索並移除重複數據,例如

Array.prototype.clean = function(){ 
 
    // Iterate backwards over array 
 
    this.reduceRight(function(acc, value, index, arr) { 
 
    // If first index of value isn't current index, remove this element 
 
    if (arr.indexOf(value) != index) arr.splice(index, 1); 
 
    }, null); 
 
    // Now sort 
 
    this.sort(); 
 
    // Return for chaining 
 
    return this; 
 
} 
 

 
var arr = 'aztatffgff'.split(''); 
 
console.log(arr.join()); 
 
console.log(arr.clean().join());

一個數組迭代向前不起作用,因爲當元件被剪接,所述元件被混洗下來,下一個被跳過。您也不能僅使用篩選器來創建陣列,因爲您無法將該新陣列分配到

reduceRight可替換爲循環。

+0

將頭部包裹起來有點困難,imo與'reduceRight'不直觀,但它完全符合我的要求。謝謝。基本上,使用'splice'是關鍵(與我的代碼相比)。 – WoodrowShigeru

+0

@ WoodrowShigeru-如果有* forEachRight *我會使用它。 ;-) – RobG