0

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>

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

oh yes I didn't thought of using filter ...Thank you, it works !
Happy to hear it helped you. Another idea may be to normalize your data get rid of array headaches. e.g. genres = {12: {id: 12, name: 'Adventure'}, /* and so on */}
1

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
      )}
    </>
  );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.