Tom Rudge
Tom Rudge

Reputation: 3272

Filter/match on an array against nested property - multiple filter

I have a simple select. The select returns a string value e.g. "foo". I then match the string value against all entries in a list. Only the entries that match return. entry.eventType.description === this.ngxValue; // "foo" === "foo" returns true

e.g single select

// this.ngxValue = "foo"

private multiEventTypeFilter(entry) {
    if (this.ngxValue === 'Any') {
        return true;
    } else {
        return entry.eventType.description === this.ngxValue;
    }
}

multi select

I've now changed my select to allow for multi selections. This now returns an array that's made up of all selected values e.g. ["foo", "bar", "car"]. So now I want to return all entries that match ANY value in that array. this.ngxValue is no longer a single string but an array with multiple strings. The below is what is desired...

entry.eventType.description === this.ngxValue; // "foo" === ["foo", "bar", "car"] returns true

Any help appreciated.

Upvotes: 1

Views: 110

Answers (3)

Nithish
Nithish

Reputation: 5999

Although Array.prototype.includes() is a straight forward way of fulfilling the requirement, there's another alternative Array.prototype.some(). Since you are looking for other alternatives, mentioning here so that it could be helpful anytime later

Below is the example how to use Array.prototype.some()

let data = ["foo", "bar", "car"]

console.log(data.some(d => d === "foo"))

And for your requirement, below is the way

return this.ngxValue.some(val => val === entry.eventType.description);

Upvotes: 2

ChrisG
ChrisG

Reputation: 2948

You should use Array.prototype.includes().

return this.ngxValue.includes(entry.eventType.description);

This will return true if the value is present in the array and false otherwise.

Upvotes: 0

Tom Rudge
Tom Rudge

Reputation: 3272

return this.ngxValue.indexOf(entry.eventType.description) !== -1;

Sorry all. I found the answer straight away. I will post here but if there are alternatives then please feel free to show.

Upvotes: 0

Related Questions