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>

>Solution :

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>

Leave a Reply