Skip to content
Tutorials Center
My learning

Topics

Lesson 132 of 156 ยท Projects

Project: Sortable, Filterable Table

Build a data table in plain JavaScript: render rows from an array, sort by any column, search and filter, paginate, and make it accessible with aria-sort.

Tables are everywhere in real software: admin panels, reports, price lists, leaderboards. A good one lets people sort by any column, search for what they need, filter by category and move through the data page by page, without reloading anything. In this project you will build such a table from scratch, in plain JavaScript, around a directory of 24 (made-up) team members.

The goal isn't just to make it work. Sorting text correctly in many languages, keeping dates from shifting across time zones, putting empty values in the right place and telling screen-reader users how the table is sorted are the details that make a table trustworthy. You will handle each one.

What you'll build

The finished table:

  • renders its header and rows from a column definition and an array of objects;
  • sorts by any column, ascending or descending, with the correct rules for text, numbers and dates;
  • shows the sort state with aria-sort, a visual arrow and a spoken announcement;
  • searches across several columns, ignoring case and accents, and highlights the match;
  • filters by team, shows "Showing 11โ€“20 of 24", and splits the rows into pages.

You will use map, filter, reduce and forEach, Sorting Arrays, Creating and Removing Elements, Bubbling, Capturing and Delegation and Formatting with Intl.

The plan: a data pipeline

Every version of the table works the same way. The original array is never changed. Each render runs it through a pipeline and draws the result:

TEXT
all rows โ†’ filter (search + team) โ†’ sort (column + direction) โ†’ paginate (page + size) โ†’ render

The state is just the user's choices: the search text, the team, the sort column and direction, the page and the page size. Each control changes one of those values and calls render(). Because the pipeline always starts from the full data, there is no "undo the last filter" logic to write. Clearing the search box simply runs the pipeline again with an empty query.

Step 1: Render the table from data

Start by describing the columns once, in an array. Each column has a key (the property in each row), a label for the header, a type that later decides how it sorts, and an optional format function. The header and every row are built from that description, so adding a column later means adding one object.

Step 1: Render rows from an array

Some choices here are about meaning, not looks:

  • <caption> names the table. Screen readers announce it when a user reaches the table, and it is the table's accessible name.
  • <th scope="col"> marks each header as the label for its column, and <th scope="row"> makes each person's name the label for their row. A screen-reader user moving to the "Projects" cell in Hana's row hears "Hana Sato, Projects, 11", not just "11".
  • Numbers are right-aligned with tabular-nums, so digits line up and you can compare sizes at a glance.
  • Missing values show a dash, styled in grey, with aria-label="No data" so the dash isn't read as "em dash".

The comment above dateFormat points at a classic bug. new Date("2019-02-11") means midnight UTC. If you format it in the visitor's own time zone and they are west of London, midnight UTC is still the previous evening for them, and "Feb 11" turns into "Feb 10". Formatting with timeZone: "UTC" shows the date exactly as stored. (The Temporal lesson shows Temporal.PlainDate, which avoids the problem entirely.)

Step 2: Sorting rules for every type

Before connecting any buttons, get the sorting logic right in the console. JavaScript's default sort() compares everything as strings, which breaks numbers and handles accents and letter case badly:

JS Step 2: Comparing text, numbers, dates and missing values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first two lines show the problem. Numbers come out as [ 1, 10, 100, 9 ], and the words as [ 'Zoe', 'apple', 'banana', 'ร‰mile' ], because uppercase letters have smaller character codes than lowercase ones, and "ร‰" comes after all of them. The collator fixes both: [ 'apple', 'banana', 'ร‰mile', 'Zoe' ], and with numeric: true, [ 'room 1', 'Room 9', 'Room 10' ].

The rest of the output shows sortRows() at work:

  • By rating, descending: Farah (4.9), Mateo (4.0), ร‰mile (3.9), Isaac (3.7), then Dana and Gustav, whose ratings are null. Empty values stay at the bottom in both directions. Nobody wants "no data" at the top of a descending list.
  • By date: 2015-04-13, 2018-12-03, 2020-05-30, 2020-09-14, 2022-03-14, 2023-01-09.
  • By projects, descending: [ 17, 10, 9, 8, 4, 3 ].
  • The last line prints Dana Kowalski: toSorted() returns a new array, so the original order is safe, which the pipeline relies on.

Three details make this robust:

  • Intl.Collator handles letter case, accents and many languages' alphabet rules. sensitivity: "base" treats "e", "E" and "รฉ" as equal for comparison, and numeric: true compares runs of digits as numbers. Create the collator once and reuse collator.compare. It is much faster than calling localeCompare() with options for every pair.
  • One comparator, flipped by a sign. Multiplying by -1 reverses the order without a second comparator. The missing-value check happens before the flip, which is why nulls stay last.
  • Stable sorting. Since ES2019, sort() and toSorted() are stable: rows that compare equal keep their previous order. Our data starts sorted by name, so a sort by team lists each team's people alphabetically with no extra work. See Sorting Arrays for more.

Step 3: Clickable, accessible sort headers

Now make the headers sortable. Each header gets a real <button>, so it works with the mouse, the keyboard and assistive technology. Clicking a new column sorts it ascending, and clicking the same column again flips the direction.

The sort state is shown three ways:

  1. aria-sort on the sorted <th>: "ascending" or "descending". Only one header should have it at a time. Screen readers announce it when the user moves into the column.
  2. An arrow next to the label, drawn with CSS from that same attribute, so the look can never disagree with what is announced.
  3. A status message ("Sorted by Projects, descending") in a visually hidden live region, so the change is announced right after the click.
Step 3: Sortable column headers

Click Projects twice to see the busiest people first, or Rating to watch the empty ratings stay at the bottom in both directions. Then sort by Team: within each team, people stay in alphabetical order, thanks to stable sorting.

The most important line is a comment: update the existing headers instead of rebuilding them. If render() rebuilt the <thead>, the button the user just pressed would be destroyed, and keyboard focus would fall back to the start of the page. The header row is built once by renderHead(). After that, render() only changes aria-sort on existing cells, and the CSS arrows follow automatically. The body is rebuilt, which is fine because nothing in it has focus.

The aria-sort attribute belongs on the <th>, not on the button, because it describes the column. Use only the values ascending, descending (and, rarely, other), and remove it from unsorted headers rather than setting none on all of them. The arrow <span> has aria-hidden="true" because the same information already comes from aria-sort.

Step 4: Search and team filter

Next, add a search box and a team dropdown. The search runs on every keystroke, which is fine for data that is already in memory (for server data, see the debouncing advice in the GitHub search project). It looks in three columns at once and ignores case and accents, so typing "emile" finds "ร‰mile" and "lucia" finds "Lucรญa".

The first match in each cell is highlighted with <mark>. The highlight is built from DOM nodes, never an HTML string, so a search for <b> can't inject markup.

Step 4: Search, filter and highlight

Type "emile", "lucia" or "izmir" (all without accents), then pick a team. Type "an" and five people match, four by name (Dana, Durand, Hana, Krishnan) and one by city (Amman): the highlight appears in whichever cell contains the text. Type something like "xyz" to see the empty state.

How it works:

  • fold() is the same normalization you used in the palindrome checker: decompose with normalize("NFD"), remove the combining marks with /\p{M}/gu, then lower-case. The query is folded once per keystroke, and each cell is folded while matching, so both sides are compared in the same form.
  • Mapping the highlight back. The search happens in the folded text, but the <mark> must wrap the original characters, accents included. Folding each character separately keeps a one-to-one record, so a match at folded positions 0โ€“4 of "emile" is drawn around "ร‰mile" in the original. It even works when the original text stores an accent as a separate combining character, which folds to an empty string.
  • The team list comes from the data. new Set(PEOPLE.map((p) => p.team)) collects each team once, and new Option(text, value) creates the <option> elements. A new team in the data appears in the dropdown automatically.
  • One input listener on the form handles both controls, because input events bubble from the text box and the <select>.
  • The empty state is a single cell with colSpan set to the number of columns, so it spans the whole table instead of squeezing into the first column.
  • role="status" on the summary makes screen readers announce "Showing 5 of 24 people" politely after each change, so users who can't see the table shrink still know the search worked.

Step 5: Pagination: the finished table

With hundreds of rows, a single long table is hard to use. The last step adds pages, puts sorting and filtering back in, and joins all three into one pipeline in a function called deriveView(). It takes the state and returns exactly what to draw:

JavaScript
function deriveView(state) {
  const filtered = PEOPLE.filter((row) => matches(row, state));
  const sorted = state.sort ? sortRows(filtered, state.sort) : filtered;
  const pageCount = Math.max(1, Math.ceil(sorted.length / state.pageSize));
  const page = Math.min(state.page, pageCount);            // never past the last page
  const start = (page - 1) * state.pageSize;
  return { rows: sorted.slice(start, start + state.pageSize), total: sorted.length, page, pageCount, start };
}

Two rules keep pagination from confusing people:

  • Changing the search, team, sort or page size goes back to page 1. If you are on page 3 and search for "lin", staying on page 3 of a two-row result would show an empty table.
  • The page is clamped. Math.min(state.page, pageCount) guarantees the page number is valid even if the data shrinks.
Step 5: The complete data table

Try a full workflow: choose 5 rows per page, sort by Joined, step through the pages with Next โ€บ, then search "engineering". The summary always tells you where you are, such as "Showing 6โ€“10 of 24", or "Showing 1โ€“5 of 8 (filtered from 24)" while a search is active.

Things to notice in the finished code:

  • State updates are copies. Each handler builds a new object with spread syntax ({ ...state, page: 1 }), the same immutable style as the to-do app. One glance at a handler tells you exactly which choices it changes.
  • deriveView() is pure. It reads the state and the data and returns plain values, with no DOM work. You could test it in the console, or reuse it unchanged if the rows were drawn as cards instead of a table.
  • The pager is rebuilt on every render, so the button that was clicked no longer exists afterwards. The handler finds the new button with the same aria-label and focuses it. Keyboard users can press Enter on Next โ€บ again and again without hunting for it.
  • aria-current="page" marks the current page for assistive technology, and the CSS uses the same attribute for the highlight. Prev and Next use aria-disabled rather than disabled at the ends, for the focus reason explained in the mini apps project.
  • <nav aria-label="Table pages"> makes the pager a named landmark that screen-reader users can jump to.

When the data is big. This table filters and sorts in the browser, which is fast for a few thousand rows. For tens of thousands, or data that lives on a server, send the state to the server instead, as query parameters such as ?q=lin&team=Design&sort=-joined&page=2&size=10, and let the database do the filtering, sorting and paging. The interface code barely changes: deriveView() becomes an async function that calls fetch(), and you protect it from out-of-order answers with an AbortController.

Bonus: nested comments, the other classic tree

Tables are flat lists. The other data shape that appears in almost every community site is a tree: comments with replies, replies to replies, and so on. The database stores them flat, one row per comment with a parentId, and the page has to show them nested. Turning one into the other is a perfect use of recursion.

The pipeline has the same flavour as the table's: flat data, then build, then sort, then draw.

  1. Build the tree. One pass over the flat list creates a map from id to node, then a second pass attaches each node to its parent (or to the root list when parentId is null). It is two simple loops and runs in linear time. A comment whose parent is missing (for example a deleted one) is treated as a root, so nothing disappears.
  2. Sort each level by votes or by date. The tree is sorted recursively, so replies are ordered within their own parent.
  3. Count descendants recursively, for the "Collapse (5 replies)" label.
  4. Limit the depth. Beyond a certain depth (say 5), real sites stop indenting and show a "continue this thread" link, because the text would run out of room.
JS Comment tree: build, sort, count

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the orphan comment from Fay is still shown, as a root. Also notice that the flat list is never changed: buildTree() copies each comment ({ ...c, replies: [] }), so you can rebuild the tree whenever votes change.

The interactive thread

Now draw it. The render function is recursive: a comment renders itself and then asks each reply to do the same. Three interactions make it feel real:

  • Reply opens a small form under that comment. Submitting adds a new entry to the flat list with the right parentId and re-renders.
  • Collapse hides the replies and shows how many are hidden. The collapsed ids live in a Set, so the state survives re-rendering.
  • Vote changes a score, and the order of siblings updates because the tree is sorted again.

Text is always inserted with textContent, so a comment containing <script> is displayed, never run. The thread is a nested list (<ul>/<li>), which gives screen readers the structure for free.

Nested comments with reply, collapse and vote

Try this: press Reply under Ben, post something, then collapse Ana's comment and see "Show 4 replies". Upvote Eli's comment a few times and watch it move above Ben's (siblings are always re-sorted). Cy's comment contains <b>not bold</b> on purpose: it appears as plain text, because we used textContent.

Details that matter:

  • The flat array is the truth. render() rebuilds the tree from it each time. There is no tree to keep in step, which removes a whole class of bugs.
  • collapsed is a Set of ids, kept outside the tree, so collapsing survives votes and new replies.
  • The vote buttons have aria-labels with the author's name, because a bare "โ–ฒ" says nothing to a screen reader, and the collapse button reports aria-expanded.
  • Re-rendering the whole tree is fine for hundreds of comments. For thousands, render only the visible branch and load more on demand.

More ideas to try

  • Remember the view in the URL. Write the state to ?q=โ€ฆ&sort=โ€ฆ&page=โ€ฆ with history.replaceState() and read it on load, so a filtered, sorted page can be bookmarked or shared (see URLs, Location and History).
  • Export to CSV. Turn the filtered and sorted rows (all pages, not just the visible one) into CSV text and download it with a Blob URL, as shown in Files and Blobs.
  • Multi-column sort. Keep an array of sort keys, and when the first comparison returns 0, try the next one.
  • Selectable rows. Add a checkbox column, a "select all on this page" checkbox in the header, and a count of selected people.
  • Column totals. Add a <tfoot> with the total projects and average rating of the filtered rows, computed with reduce().

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [10, 9, 1, 100].toSorted() return?

    Without a compare function, values are converted to strings and compared character by character, so "100" comes before "9". Use (a, b) => a - b for numbers.
  2. 2. In sortRows(), why is the missing-value check done before multiplying by sign?

    If the check were flipped by the sign, empty values would jump to the top when sorting descending. Keeping it outside the flip pins them to the end.
  3. 3. Where should the aria-sort attribute go, and what should unsorted columns have?

    aria-sort describes a column, so it belongs on its header cell. Only one header should carry it at a time.
  4. 4. Why does the table update the existing header cells instead of rebuilding the <thead> on every render?

    Elements that are removed can't keep focus. Building the header once and only changing attributes keeps the focused button in place.
  5. 5. You are on page 3 and type a search that matches 4 rows (10 rows per page). What should happen?

    Changing a filter resets the page to 1, and deriveView() also clamps the page to the last existing page, so the user never sees an empty page by mistake.

Summary

  • Describe the columns once (key, label, type, format), and build both the header and the rows from that description.
  • Treat the original data as read-only and run a pipeline on every render: filter โ†’ sort โ†’ paginate โ†’ draw.
  • Sort text with a reusable Intl.Collator (numeric: true, sensitivity: "base"), numbers with a - b, ISO dates with Date.parse(), and keep missing values last in both directions. toSorted() is stable and leaves the original array alone.
  • Format date-only strings with timeZone: "UTC", or they can appear one day early.
  • Use <caption>, <th scope="col">, <th scope="row"> and buttons inside the headers. Put aria-sort on the one sorted <th>, and announce changes in a role="status" region.
  • Search with folded text (no case, no accents), highlight with DOM nodes, and show an empty state with colSpan.
  • Reset to page 1 on any filter or sort change, clamp the page, mark it with aria-current="page", and keep focus on the pager after re-rendering.
  • A comment thread stores a flat list with parentId; build the tree in two passes with a Map, sort and count recursively, and keep UI state (collapsed ids) in a Set outside the tree.

Next: Data Structures in JavaScript