user12919356
user12919356

Reputation:

Find the same elements of an array from other arrays?

I have a movie, I want to show films of the same genres, what am I doing wrong?

My film (find):

{
    "id": 1,
    "title": "Kill Bill",
    "genre_ids": [1, 10, 15]
}

// All films (movies)

{
    "id": 2,
    "title": "Leon",
    "genre_ids": [1, 12, 15]
},
{
    "id": 3,
    "title": "Spider-man",
    "genre_ids": [12, 32, 15]
},
{
    "id": 3,
    "title": "Marvel cap",
    "genre_ids": [20, 38, 1]
},

// My code

    return find.map(i => { // My film
        return i.genre_ids.map(ids => {
            return movies.data.results.filter(movie => { // All films
                return movie.genre_ids.filter(idMov => idMov === ids)
            })
        })
    });

Upvotes: 1

Views: 68

Answers (1)

Drew Reese
Drew Reese

Reputation: 202658

Your movie (find) is an object, not an array, it doesn't have a map function to call.

A Solution:

Create a function that can from a single genre and array of movies return an array of matching movies by genre

const matchByGenre = movies => genre =>
  movies.filter(movie => movie.genre_ids.includes(genre));

Iterate over the film's genre_ids array for matches. This yields an array of array matches, flatten them with .flat to a single array. The set is used to remove duplicates and have the result returned back to you as array.

const movieSet = Array.from(
  new Set(film.genre_ids.map(matchByGenre(movies)).flat())
);

const film = {
  id: 1,
  title: "Kill Bill",
  genre_ids: [1, 10, 15]
};

const movies = [
  {
    id: 2,
    title: "Leon",
    genre_ids: [1, 12, 15]
  },
  {
    id: 3,
    title: "Spider-man",
    genre_ids: [12, 32, 15]
  },
  {
    id: 4,
    title: "Marvel cap",
    genre_ids: [20, 38, 1]
  },
  {
    id: 5,
    title: "The Big Lebowski",
    genre_ids: [20, 38, 2]
  }
];

const matchByGenre = movies => genre =>
  movies.filter(movie => movie.genre_ids.includes(genre));

const movieSet = Array.from(
  new Set(film.genre_ids.map(matchByGenre(movies)).flat())
);

console.log(movieSet);

Note: If the syntax for matchByGenre is confusing, it is a curried function taking a movies array and returns a callback function to be used by array::map

Upvotes: 3

Related Questions