Skip to main content

Search

Search problems, hooks, and pages

Sortable Employee Table

Render 10 static employee records in a table. Expose a few sortable fields as clickable chips (Name, Age, Salary); clicking a chip sorts the dataset by that field, and clicking the active chip again flips the direction between ascending and descending. No API call — the data is hard-coded.

Requirements

  • Render the static employee list in a table (name, age, department, salary)
  • Show a chip per sortable field (2–3 chips)
  • Clicking a chip sorts the rows by that field
  • Clicking the already-active chip toggles asc ↔ desc
  • Indicate the active field and direction (highlight + ↑/↓ arrow)
  • Sort strings and numbers correctly (localeCompare vs numeric subtraction)
  • Keep styling minimal — focus on the sort logic and state, not visual polish

Key Patterns

sort state = { key, dir } — a single descriptor, not one flag per columnsorted rows derived via useMemo from (data, sort) — never stored in statesort a COPY: [...data].sort(...) — Array.sort mutates in placenumeric compare (a - b) vs string localeCompare, scaled by a ±1 direction factor

Important

Interview Tip

Model sorting as one { key, dir } object rather than a separate flag per column — it makes "only one active sort at a time" automatic and the toggle trivial. Always sort a copy ([...data]) because Array.prototype.sort mutates in place; mutating the source array is a subtle bug that corrupts your "unsorted" baseline. Use a direction factor (asc ? 1 : -1) so one comparator handles both directions, and branch on field type: numeric fields use (a - b), string fields use localeCompare.
Sort by:
NameAgeDepartmentSalary
Aarav Sharma29Engineering$92,000
Diya Patel34Design$78,000
Vihaan Reddy41Engineering$120,000
Ananya Iyer26Marketing$64,000
Kabir Nair38Sales$85,000
Ishika Gupta31Design$73,000
Rohan Mehta45Engineering$134,000
Saanvi Joshi28Marketing$69,000
Arjun Verma36Sales$88,000
Myra Bose33Engineering$98,000