Home > Blockchain >  Find same value from array inside object
Find same value from array inside object

Time:11-06

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>

CodePudding user response:

That's because forEach doesn't return anything it only executes your function. (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

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