Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I select only the items with different names in an array?

I’m mapping data from an array and some of the data have the same name so I would like to display them only once and not multiple time. I’m using React and here’s the api link.

Here’s my code (it’s just a simple map) :

{machines.filter((machines) => {
  if (search === "") {
    return machines
  } else if (machines.move.name.replace(/-/g, ' ').toLowerCase().includes(search.toLowerCase())) {
    return machines
  }
})
.map((ma) => 
                                        
  <tr key={ma?.id} className='machines_table_body_row'>
    <td className='machines_table_body_row_name'>
      {ma?.item?.name.toUpperCase()}
    </td>
    <td className='machines_table_body_row_element'>
      <Link
        to={`/moves/${ma?.move?.name}`}
        key={ma?.move?.name}
      >
        {ma?.move?.name.replace(/-/g, ' ')}
      </Link>
    </td>
  </tr>
)}

What I’d like is having the first with tm01, tm02, tm03, etc only once and the second with all the different attacks (but here also without repetitions).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could create a filtered array and then map on it. Below is how to create that filtered array :

const filtredMachines = [];
machines.forEach(ma => {
  if(!filtredMachines.some(m=>m.move.name === ma.move.name)){
     filtredMachines.push(ma)
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading