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

37 views Asked by At

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?

2

There are 2 answers

0
zfrisch On BEST ANSWER

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);
})
0
Zohaib Ijaz On

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