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 would you group a field in a table so it doesnt show duplicates – react

On a webpage for an alumni group, I’m trying to manage teams, and in the teams table, I have the fields: year, team_category(Football, etc), and members(MtoM). I’m trying to show on the first page a list of categories but only one per field entry. Clicking on the category button would lead to a list of teams filtered by said category and show year and members of the team. So my example below would just be Football, Cheearleading, chess. How to I group by category or any potentially better method?

import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { getTeams } from "../../../api/apiCalls";

const Teams = () => {
  const [teams, setTeams] = useState([]);
  useEffect(() => {
    getTeams()
      .then((response) => {
        console.log(response.data);
        setTeams(response.data);
      })
      .catch((error) => {
        console.log(error.message);
      });
  }, []);

  return (
    <div className="">
      <h1>
        Teams
        <hr />
      </h1>
      {teams.map((teams, index) => (
        <div className="" border="" key={teams.id}>
          <Link
            className="btn btn-outline-dark btn-warning m-1"
            to={`/dashboard/teams/${teams.category}/`}
          >
            {teams.category}
          </Link>
        </div>
      ))}
    </div>
  );
};

Output for my code

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 can use reduce to only include the category once

teams.reduce((previousValue, currentValue) => {
  return previousValue.some((team) => team.category === currentValue.category)
    ? previousValue
    : [...previousValue, currentValue];
}, []).map... your code here
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