2017-06-20 15 views
0

我想過濾使用多個過濾器的數組。但到目前爲止,我還沒有成功獲得我期待的。使用typeScript過濾mutidimensionnal數組

這是過濾myVar的之前我的組件角

list = [ {type: type1, code: code1}, {type: type2, code: code2}] 

searchElement(code?: string, type?: string){ 
var myVar = this.list 

if(type) 
myVar = myVar.filter(elt => elt.type.indexOf(type) > -1); 

if(code) 
myVar = myVar.filter(elt => elt.type.indexOf(code) > -1); 

//call another function myFunction() with the filtered array myVar 
} 

由於異步行爲myFunction()被調用。如何在致電myFunction()之前確保myVar已過濾?

+1

尋求幫助時,請一定要格式化/縮進你在一個合理的,一致的方式代碼,使其更容易爲人們幫助您閱讀它。 (這樣做總是非常有用,所以* * *更容易閱讀。) –

+0

注意:這不是一個多維數組。這是一組對象。 (從技術上講,JavaScript沒有多維數組,它有數組數組,例如'[[],[],[]]';人們往往認爲它們是多維數組,但是這是一個數組的對象而不是陣列數組,因此完全不像MD陣列。) –

回答

1

您需要一個filter回調同時使用過濾器值,而不是使用多個filter電話:

list = [ {type: type1, code: code1}, {type: type2, code: code2}]; 

searchElement(code?: string, type?: string){ 
    var myVar = this.list; 

    if (type || code) { 
     myVar = myVar.filter(elt => (!type || elt.type.indexOf(type) > -1) && (!code || elt.code.indexOf(code) > -1)); 
    } 

    // ... 
} 

注意每一個條件是怎樣的形式!filterValue || useTheFilterValue這樣,如果沒有過濾器值,該條件得到滿足,並且如果存在,則只有在過濾器匹配時才滿足。

我假定需要「和」匹配,這就是爲什麼我加入了&&這兩個篩選檢查。例如,如果你同時提供typecode,我假設兩者必須匹配才能保留陣列中的元素。

(另外,你檢查codeelt.type,而不是elt.code