i want to filter an array by some specific names
genres = [
{id: 1, name: 'Action'},
{id: 2, name: 'Comedy'},
{id: 3, name: 'Documentary'},
{id: 4, name: 'Action'},
{id: 5, name: 'Comedy'},
]
// in here i get only Action
genres.filter(i => i.name.includes("Action"))
output = [
{id: 1, name: 'Action'},
{id: 4, name: 'Action'},
]
// in here i get only Comedy
genres.filter(i => i.name.includes("Comedy"))
output = [
{id: 2, name: 'Comedy'},
{id: 5, name: 'Comedy'},
]
But i want to get both Action and Comedy like this:
[
{id: 1, name: 'Action'},
{id: 4, name: 'Action'},
{id: 2, name: 'Comedy'},
{id: 5, name: 'Comedy'},
]
How can i do it?
CodePudding user response:
genres.filter(i => i.name.includes("Action") | i.name.includes("Comedy"))
or
genres.filter(i => ["Action","Comedy"].includes(i.name))
CodePudding user response:
Use an OR operator to check on both conditions
genres = [
{id: 1, name: 'Action'},
{id: 2, name: 'Comedy'},
{id: 3, name: 'Documentary'},
{id: 4, name: 'Action'},
{id: 5, name: 'Comedy'},
]
// Use a OR operator to check both conditions
result = genres.filter(i => i.name.includes("Action") || i.name.includes("Comedy"))
console.log(result)
CodePudding user response:
You can do:
const genres = [{id: 1, name: 'Action'},{id: 2, name: 'Comedy'},{id: 3, name: 'Documentary'},{id: 4, name: 'Action'},{id: 5, name: 'Comedy'},]
const result = genres.filter(({ name }) => ['Action', 'Comedy'].includes(name))
console.log(result)