I have an array of objects containing information about movies. Every object has a value for genre. That value can be either a string or an array.
I am fetching a genre from the query string and saving it to a variable called genre. Now I want to sort out only the movies in that genre.
My array of objects look like this:
movies = [
{
title:"Apocalypse Now",
year: "1979",
genre: [
"drama",
"war"
]
},
{
title:"Unforgiven",
year: "1992",
genre: [
"western",
"drama"
]
},
{
title: "The big Lebowski",
year: "1998",
genre: "comedy"
}
];
Now I have found a solution that works. But I am not happy with it because:
It doesn't allow for more than 3 genres for every movie.
It doesn't look pretty and doesn't compose well with other code. And I'm thinking there has got to be a better way but I can't find it.
Here is what I have now:
var genre = req.query.genre;
var movies = data.movies;
var filtered = movies.filter(function(x){
return x.genre == genre || x.genre[0] == genre || x.genre[1] == genre || x.genre[2] == genre;
});
since x can be a string or an array it's a simple matter of testing equality if it's a string, or using indexOf if it's an array
var genre = req.query.genre;
var movies = data.movies;
var filtered = movies.filter(function(x){
return typeof x == "string" ? x == genre : x.indexOf(genre) >= 0;
});
note: modern browsers you could use
return typeof x == "string" ? x == genre : x.includes(genre);
Just use indexOf()
var genre = req.query.genre;
var movies = data.movies;
var filtered = movies.filter(function(x){
return x.genre.indexOf(genre) > -1;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With