edkeveked
edkeveked

Reputation: 18401

filter mutidimensionnal array using typeScript

I am trying to filter an array using more than one filter. But so far I haven't succeeded to get what I am expecting.

this is my component Angular

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
}

Because of the asynchronous Behavior myFunction() is called before myVar is filtered. How can I make sure that myVar is filtered before calling myFunction()?

Upvotes: 0

Views: 64

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075745

You need to use both filter values in one filter callback, rather than using multiple filter calls:

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));
    }

    // ...
}

Notice how each condition is in the form !filterValue || useTheFilterValue so that if there is no filter value, that condition is satisfied, and if there is, it's only satisfied if the filter matches.

I've assumed an "and" match is required, which is why I joined the two filtering checks with &&. E.g., if you supply both type and code, I assume both must match in order to keep an element in the array.

(Also, you were checking code against elt.type instead of elt.code.)

Upvotes: 1

Related Questions