Joon Joonam
Joon Joonam

Reputation: 88

Checking and displaying values of array compared to another array in React

One data set is an object of arrays of ids and another is an object of arrays of ids and names. What I'd like to do is check if the ids from the first data exist in the second data set and if they do then display the names.

This is what is being called by the component, which works correctly:

<td>Genre</td>
<td>{this.matchGenres(this.props.movie.genre_ids, this.props.genres)}</td>

And this is the function that I can't get to work:

matchGenres = (genres, genreList) => {

    genres.forEach((genre) => {
      genreList.filter((list) => {
         return list.id === genre;
      }).map((newList) => {
         return newList.name;
      });
    });

  }

It looks like the operation performs correctly and returns the right names when I console.log it! But! its not showing up in the component on render.

Upvotes: 0

Views: 763

Answers (3)

Joon Joonam
Joon Joonam

Reputation: 88

This is the solution that ended up working:

if (genreList.length !== 0) {
  return genres.map(genre => genreList.find(list => list.id === genre)).map((newList) => newList.name) + ',';
}

For some reason the value of GenreList, which is an array, was showing up as empty for the first couple times the function is call. Thats another problem I'll have to look at but the if statement solves for it for the time being.

Upvotes: 0

kiranvj
kiranvj

Reputation: 34107

But! its not showing up in the component on render.

Its because your function doesn't return anything. You return inside filter and map and your function does not return anything. Also note that forEach always return undefined

You just need a minor change. Try this

let genres = ["1", "2", "3"];
let genreList = [{
  id: "2",
  name: "Two"
}, {
  id: "32",
  name: "Three"
}]

matchGenres = (genres, genreList) => {

  return genreList.filter((list) => {
    // findIndex return array index if found else return -1 if not found
    return genres.findIndex(genere => genere === list.id) > -1;
  }).map(list => list.name);

}

console.log(matchGenres(genres, genreList));

Upvotes: 1

IvanD
IvanD

Reputation: 2923

const genres = [{
  id: 1,
  name: "Jazz Music"
}, {
  id: 2,
  name: "Something"
}];

const genreList = [1, 10, 100];

matchGenres = (genres, genreList) => genres
  .filter(genre => genreList.includes(genre.id))
  .map(genre => genre.name);

const matchedGenres = matchGenres(genres, genreList);

console.log(matchedGenres);

Upvotes: 1

Related Questions