Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    } 
  });
});
like image 895
user3015195 Avatar asked Sep 05 '25 03:09

user3015195


2 Answers

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))
like image 98
CRice Avatar answered Sep 07 '25 20:09

CRice


Convert array=movies to Set first (it will improve performances when array=movies has a ton of elements), then use reduce to pull out all match items.

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

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

let indexes = new Set(movies)

console.log(
  genres.reduce((pre, cur) => {
    indexes.has(cur.id) && pre.push(cur.name)
    return pre
  }, [])
)
like image 42
Sphinx Avatar answered Sep 07 '25 19:09

Sphinx