samuel potter
samuel potter

Reputation: 209

Find same value from array inside object

I'm trying to display the content of an object depending of the content of an arrray. This is the data.

const genres = [
               {id: 12, name: 'Adventure'},
               {id: 28, name: 'Horror'},
               {id: 1204, name: 'Western'}
]

const typeIds = [12, 65, 45, 12, 28, 1204]

So what I would like to do, is to print the name of the genres when it matches the typeIds.

For this I made a forEach followed by a map but when I return the html balise, I don't receive anything on my page.

<ul className={`${isHover ? 'block' : 'hidden' } flex space-x-3 text-white font-semibold pb-5`}>
                {
                    genres.forEach(element => {
                        typeIds.map((res, key) => {
                            if (element.id === res) {
                                return (
                                    <li key={key}>{element.name}</li>
                                )
                        }
                    })
                })}
            </ul>

Upvotes: 0

Views: 36

Answers (2)

DecPK
DecPK

Reputation: 25408

SOLUTION 1

You can make it efficient using Set as

Live Demo

Codesandbox Demo

1) Create a Set as of id's in genres

  const genres = [
    { id: 12, name: "Adventure" },
    { id: 28, name: "Horror" },
    { id: 1204, name: "Western" }
  ];

  const typeIds = [12, 65, 45, 12, 28, 1204];
  const dict = new Set(typeIds);

2) then you can use filter and map to get only the object that exist in the Set.

{genres
  .filter((o) => dict.has(o.id))
  .map((o) => (<div key={o.id}>{o.name}</div>)
  )}

SULUTION 2

You can also achieve the exact same result without using filter as

Live Demo

Codesandbox Demo

  const genres = [
    { id: 12, name: "Adventure" },
    { id: 28, name: "Horror" },
    { id: 1204, name: "Western" },
    { id: 100, name: "Fast" }
  ];

  const typeIds = [12, 65, 45, 12, 28, 1204];
  const dict = new Set(typeIds);
  return (
    <>
      {genres.map((o) =>
        dict.has(o.id) ? <div key={o.id}>{o.name}</div> : null
      )}
    </>
  );

Upvotes: 1

amirhe
amirhe

Reputation: 2341

That's because forEach doesn't return anything it only executes your function. (MDN)

consider creating your list and map over it.

const selectedItems = genres.filter(g => typeIds.includes(g.id))

<ul {...props}>
{selectedItems.map(element => <li key={element.id}>{element.name}</li>)}
</ul>

Upvotes: 1

Related Questions