tomtom
tomtom

Reputation: 642

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

Upvotes: 3

Views: 4176

Answers (3)

baao
baao

Reputation: 73211

Just use indexOf()

var genre = req.query.genre;
var movies = data.movies;
var filtered = movies.filter(function(x){
    return x.genre.indexOf(genre) > -1;
});

Upvotes: 1

Train
Train

Reputation: 3496

I would change the way you set up the data, make everything an array of strings even if it is just one value. It should be consistent. If you are using es6 or 7 you can use arrow functions. This way you can use as many genre's as you want instead of just 3 at max.

    for(let i = 0; i < movies.length; i++){
    `var genre = movies[i].genre.filter(x => x.genre == "comedy");`
//do something with the value
    } 

Upvotes: -1

Jaromanda X
Jaromanda X

Reputation: 1

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

Upvotes: 3

Related Questions