Search code examples
javascriptarraysrefactoring

Best way to find matching id's in an array of objects?


if I have this array of movie ids

movies = [28, 14, 100, 53, 37]

and this array of objects.

genres = [
      {id: 28, name: "Action"},
      {id: 10770, name: "TV Movie"},
      {id: 53, name: "Thriller"},
      {id: 10752, name: "War"},
      {id: 37, name: "Western"}
    ]

I would like to return an array of the matching ids. example [ 'Action', 'Thriller', 'Western' ].

I have a solution already but feel that it could be better. What is the best way to refactor this code? Thanks.

genre_array = []
movies.forEach(function(e){
  genres.forEach(function(element){
    if (element.id == e) {
     genre_array.push(element.name)
    } 
  });
});

Solution

  • I would combine the filter and map array methods. Use filter to get a list of genres that are in your movies array, then use map to convert that to a list of names.

    Example:

    const movies = [28, 14, 100, 53, 37]
    
    const genres = [
          {id: 28, name: "Action"},
          {id: 10770, name: "TV Movie"},
          {id: 53, name: "Thriller"},
          {id: 10752, name: "War"},
          {id: 37, name: "Western"}
        ]
    
    // I would like to return an array of the matching ids. example [ 'Action', 'Thriller', 'Western' ].
    
    console.log(genres.filter(g => movies.includes(g.id)).map(g => g.name))