Onyx
Onyx

Reputation: 5782

Can I use .includes() to determines whether an array includes a certain element based on an array of strings instead of a single string?

Right now if I use this snippet of code, I get all elements whose region property is "Demacia"

let filtered = this.cards.filter((card) => {
    return card.region.includes("Demacia");
})

Now I want to be able to get all elements whose property region is either "Noxus" or "Demacia", however, this doesn't seem to work as it returns an empty array

let regions = ["Demacia", "Noxus"];

let filtered = this.cards.filter((card) => {
    return card.region.includes(regions);
})

Can I even do that or do I need to look into other array functions?

Upvotes: 0

Views: 36

Answers (2)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

Just adding my answer because Array.prototype.includes() is not supported in IE, so if you want to support old browser, you can do

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility

let regions = ["Demacia", "Noxus"];

let filtered = this.cards.filter((card) => {
    return regions.indexOf(card.region) > -1;
})

Upvotes: 1

zfrisch
zfrisch

Reputation: 8660

Instead of trying to pass multiple options to includes, look inside regions to see if it contains the region of the current card

let regions = ["Demacia", "Noxus"];

let filtered = this.cards.filter((card) => {
    return regions.includes(card.region);
})

Upvotes: 4

Related Questions