I am trying to filter name of genres for a movie based on ids. so if id matches I get that name out.
const genres = [
{ id: 28, name: "Action" },
{ id: 12, name: "Adventure" },
{ id: 16, name: "Animation" },
{ id: 35, name: "Comedy" },
{ id: 80, name: "Crime" },
{ id: 99, name: "Documentary" },
{ id: 18, name: "Drama" },
{ id: 10751, name: "Family" },
{ id: 14, name: "Fantasy" },
{ id: 36, name: "History" },
{ id: 27, name: "Horror" },
{ id: 10402, name: "Music" },
{ id: 9648, name: "Mystery" },
{ id: 10749, name: "Romance" },
{ id: 878, name: "Science Fiction" },
{ id: 10770, name: "TV Movie" },
{ id: 53, name: "Thriller" },
{ id: 10752, name: "War" },
{ id: 37, name: "Western" },
];
const genre_ids = [10752, 10770, 18, 12]
You can filter genres using genre_ids and then map the specific values
function filterGenres(genres, ids) {
return genres
.filter((genre) => ids.indexOf(genre.id) != -1)
.map((genre) => genre.name)
}
or alternatively use the reduce function
function filterGenres(genres, ids) {
return genres.reduce((results, genre) => {
if(ids.indexOf(genre.id) != -1) {
results.push(genre.name);
}
return results;
}, []);
}
The below may be one possible solution to achieve the desired objective.
Code Snippet
const getNames = (ids, objects) => (
ids.map(el => (
objects.find(
({id}) => id === el
)?.name
))
);
// below will be better in performance
// but the names returned will be ordered based on 'genres' array
// objects.filter(({id}) => ids.some(el => el === id))
// .map(({name}) => name)
const genres = [
{ id: 28, name: "Action" },
{ id: 12, name: "Adventure" },
{ id: 16, name: "Animation" },
{ id: 35, name: "Comedy" },
{ id: 80, name: "Crime" },
{ id: 99, name: "Documentary" },
{ id: 18, name: "Drama" },
{ id: 10751, name: "Family" },
{ id: 14, name: "Fantasy" },
{ id: 36, name: "History" },
{ id: 27, name: "Horror" },
{ id: 10402, name: "Music" },
{ id: 9648, name: "Mystery" },
{ id: 10749, name: "Romance" },
{ id: 878, name: "Science Fiction" },
{ id: 10770, name: "TV Movie" },
{ id: 53, name: "Thriller" },
{ id: 10752, name: "War" },
{ id: 37, name: "Western" },
];
const genre_ids = [10752, 10770, 18, 12];
console.log(getNames(genre_ids, genres));
Explanation
getNames is used to obtain the resultgenre_ids arraygenres (by matching the id prop)name prop from the matched genres elementCommented-out method:
genres and destructure to obtain just the idid is present in the genre_ids array.map to destructure just the namenames is returned (implicitly)This method returns in a different order (based on the genres array).
are you trying something like this -
let genre_names = new Array();
for(let i=0; i<genre_ids.length; i++) {
var a = genres.find(x=>x.id == genre_ids[i]);
if (!!a)
genre_names.push(a.name);
}
console.log(genre_names);
resulting with [War,Tv Movies, drama, Adventure] ?