AniUI Academy

Build a sortable data table

mediumUI ComponentsHigh freq+200 XP

Render a table of people with columns Name, Age and City. Clicking a column header sorts the rows by that column.

A header cycles through three states on repeated click: ascending → descending → none (original order). Only one column is sorted at a time — clicking a new header resets the previous one.

Examples

// Initial — Priya, Omar, Ana, Kenji, Zara (all aria-sort="none")

// Click header-name → Ana, Kenji, Omar, Priya, Zara
//                     header-name aria-sort="ascending"

// Click header-name again → Zara, Priya, Omar, Kenji, Ana
//                           aria-sort="descending"

// Click header-name a third time → original order
//                                   aria-sort="none"

Three-state cycle on one column; a fresh column always resets the previous one.

const sortedRows =
  sort.column === null || sort.direction === "none"
    ? PEOPLE
    : [...PEOPLE.map((row, i) => [row, i])]
        .sort(([a, ai], [b, bi]) => {
          if (a[sort.column] === b[sort.column]) return ai - bi;
          const sign = sort.direction === "ascending" ? 1 : -1;
          return a[sort.column] < b[sort.column] ? -sign : sign;
        })
        .map(([row]) => row);

Tagging rows with their original index is how you guarantee stability — the index breaks ties.

What it has to do

  • Each column header is a `<button data-testid="header-{name|age|city}">`.
  • Each sortable header reflects state via `aria-sort="ascending"`, `"descending"` or `"none"`.
  • Rows are `<tr data-testid="row">` elements rendering `.name`, `.age`, `.city` as plain text cells.
  • First click sorts ascending; second click on the same header sorts descending; third click returns to the original order.
  • Clicking a different header resets the previous header's `aria-sort` to `"none"` and starts fresh on the new column.
  • Sorting must be stable — two rows with the same sort key preserve their original relative order.

Notes

  • Never mutate the source array (`PEOPLE.sort(...)`) — React would reuse keys against the wrong rows. Spread first, or `[...PEOPLE]`.
  • `Array.prototype.sort` has been stable in V8 and SpiderMonkey since 2019 — but relying on it is risky across runtimes. Use an explicit tiebreaker.
  • `aria-sort` lives on the column header. Reset it on the previously sorted column when the active column changes; a screen reader otherwise reports two columns sorted at once.
  • For >~1000 rows, memoize the sorted array with `useMemo` keyed on `(column, direction)` — re-sorting on every unrelated re-render shows up on long tables.
Asked atGoogleMicrosoftAmazonAtlassianLinkedInStripe

Stuck? The react course covers the ideas this problem is built on.

import { useState } from "react";

const PEOPLE = [
  { name: "Priya", age: 29, city: "Bengaluru" },
  { name: "Omar", age: 34, city: "Dubai" },
  { name: "Ana", age: 29, city: "Lisbon" },
  { name: "Kenji", age: 41, city: "Tokyo" },
  { name: "Zara", age: 29, city: "Karachi" },
];

export default function App() {
  const [sort, setSort] = useState({ column: null, direction: "none" });

  // TODO: derive sortedRows from PEOPLE based on sort.column + sort.direction.
  // Remember: stable sort, three-state cycle, only one active column.
  const sortedRows = PEOPLE;

  return (
    <table style={{ fontFamily: "sans-serif", borderCollapse: "collapse", padding: 16 }}>
      <thead>
        <tr>
          {["name", "age", "city"].map((col) => (
            <th key={col}>
              <button
                data-testid={`header-${col}`}
                aria-sort="none"
                style={{ padding: 8, cursor: "pointer" }}
              >
                {col.toUpperCase()}
              </button>
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {sortedRows.map((person, i) => (
          <tr key={i} data-testid="row">
            <td style={{ padding: 8 }}>{person.name}</td>
            <td style={{ padding: 8 }}>{person.age}</td>
            <td style={{ padding: 8 }}>{person.city}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

5 tests · +200 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.