2017-09-05 45 views
0

我有這個在我的.ts文件:如何從數組中刪除重複的名稱?

search(event) { 
    this.autocompletedata.filter((entry) => { 
     console.log('entryyyy',entry); 
     if (this.showFilter == 1) { 
      this.results = entry['items'].filter(a => a['item'] ? a['item'].startsWith(event.query) : false); 
     } 
     else if (this.showFilter == 2) { 
      this.results = entry['items'].filter(a => a['service'] ? a['service'].startsWith(event.query) : false); 
     } 
     else if (this.showFilter == 3){ 
      this.results = entry['items'].filter(a => a['phoneNum'] ? a['phoneNum'].startsWith(event.query) : false); 
     } 

    }); 
} 

問題是,我得到的數據,但我得到的重複數據。任何建議如何從數組中刪除重複的數據?

這是我完整的自動完成代碼。

這是我的項目的結構:

enter image description here

現在,在過去的if語句我有結果,他們建議,因爲在陣列我有多次相同數量的我建議得到該號碼,我不想要那個 - 我只想要顯示一個。

+0

使用過濾器代替的forEach並根據病情 –

+0

我有數組中的數組 – uzhas

+0

然後使用過濾器過濾器內返回true或false 。並保持你的結局! –

回答

0

嘗試下面的代碼,在你的代碼中你使用內部項過濾器,但不是原始數組,這是值;

this.result = this.autocompletedata.filter((entry) => { 
     if (this.showFilter == 1) { 
      entry['item'] = entry['items'].filter(a => a['item'] ? a['item'].startsWith(event.query) : false); 
      return true; 
     } 
     return false; 
    }); 
+0

調整以獲得實際結果 –

+0

這不起作用...我沒有獲取數據 – uzhas

0

使用array.filter功能來過濾重複陣列象下面這樣:

// Array with duplicate names 
autocompletedata: Array<string> = ['a','b','v','c','p','a','b']; // For ex 
output: Array<string> = []; // this will hold array filtered with duplicate one 

let names: string = ''; 
this.output = this.autocompletedata.filter((item, index) => { 
    var flag = names.indexOf(item)===-1; // check if item available or not 
    names = index === this.autocompletedata.length-1? '': `${names}${item}`; // creating string of items to compare duplicate names 
    return flag; // return true if item is not duplicate one 
}) 
+0

您可以添加一些關於您的代碼如何回答問題的解釋嗎?代碼轉儲不是很容易從 –

+1

中學習更新並附上解釋。 –