Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter array within array of objects in javascript?

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:

  1. It doesn't allow for more than 3 genres for every movie.

  2. 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;
      });
like image 529
tomtom Avatar asked Apr 23 '26 08:04

tomtom


2 Answers

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);
like image 183
Jaromanda X Avatar answered Apr 25 '26 22:04

Jaromanda X


Just use indexOf()

var genre = req.query.genre;
var movies = data.movies;
var filtered = movies.filter(function(x){
    return x.genre.indexOf(genre) > -1;
});
like image 42
baao Avatar answered Apr 25 '26 22:04

baao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!