Home > OS >  How can I show only one Item from same name in react?
How can I show only one Item from same name in react?

Time:08-16

in my backend data i have list of same name of sectors name like this and it have different of id every item but has the same sector. so I want only to reduce the same sector name

  • Energy

  • Energy

  • Envirnment

  • Goverment

  • Envirnment

  • Aerospace & defence

  • Aerospace & defence

  • Manufacturing

  • Retail

  • Manufacturing

but I just want only one name with same value like this

  • Energy

  • Envirnment

  • Goverment

  • Aerospace & defence

  • Manufacturing

  • Retail

Here is my code

const Home = () => {
  const [assignData, setAssignData] = useState([]);

  const datalist = async () => {
    const result = await fetch("http://localhost:5000/api/getalldata");
    const dresult = await result.json();
    setAssignData(dresult);
    
  };
  
  useEffect(() => {
    datalist();
  }, []);

  return (
    <>
      {assignData.map((data) => {
        return (
          <>
          <h1> {data.sector} </h1>
         
          </>
        )
      })}
    </>
  );
};

export default Home;

CodePudding user response:

If you're only after unique sector properties, you can map your assignData array to an array of strings and push that through a Set to get only unique values.

Here I've used a memo hook to create the sectors array and keep it in sync with assignedData.

const sectors = useMemo(
  () => [...new Set(assignData.map(({ sector }) => sector))],
  [assignData]
);

return sectors.map((sector) => <h1 key={sector}>{sector}</h1>);

CodePudding user response:

You could turn assignData into a Set and convert it back to an array. This will remove duplicates from the array.

{[... new Set(assignData)].map((data) => {
  return (
    <>
      <h1> {data.sector} </h1>
    </>
  )
})}
  • Related