2017-08-05 33 views
0

我已經集成Bootstrap3-typeahed在我的項目中,一切工作正常。問題是我在MySQL數據庫中有重複的條目,我需要閱讀的屬性,但不希望它們在自動完成/建議下拉列表中多次顯示。

如何從Bootstrap-3-Typeahead返回的結果中刪除重複項?

例如,用戶在輸入域結果 'BAB' 被示: BAB BLE BAB BLE BAB BLER。

結果是我想要實現的是:BAB BLE BAB BLER

這裏是響應用於顯示結果的代碼:我試圖清理結果在這個

   $.ajax({ 
        url:"engine/searchhandler.php", 
        method:"POST", 
        data: {query:query, lang:$('#lang-pseudo').val()}, 
        dataType:"json", 
        async: false, 
        success:function(data){ 
         result($.map(data, function(item) { 
          return item; 
         })) 
        } 
       }) 

但它似乎沒有工作(日誌顯示空元素):

    success:function(data){ 
         result($.map(data, function(item) { 
          var list = new Array();          
          var unique = list.filter(function(elem, index, self) { 
           return index == self.indexOf(elem); 
          }) 
          console.log(unique); 
          //return item; 
         })) 
        } 

Can有人幫助我從結果中刪除重複項?

回答

1

使用Set

如果data包含您的數組:

const withoutDupes = [...new Set(data)]; 

Set s只能包含唯一的值。 [...]Set轉換回數組。

沒有Set

// 'data', not 'list' 
const withoutDupes = data.filter(function(elem, index, self) { 
    return index === self.indexOf(elem); 
}); 
+0

類型withoutDupes的將是一個數組? – iColdBeZero

+0

是的。 '[... new Set(data)]'和'Array.prototype.filter'都返回一個數組。 – PeterMader

+0

這是一個很好的答案,謝謝,但是在我沒有使用Dupes之後,我不知道如何返回它的每個元素 – iColdBeZero