In short
'Price: low to high' is one of the most clicked buttons in online shopping. Sorting looks small, but getting it right with pagination is a classic interview question.
Letting users reorder a data set by a chosen field (price, date, name), typically via a `sort`/`order` query parameter sent to the API.

Think of it like this
The IPL points table
The same ten teams can be ordered by points, by net run rate or by name. Nothing about the teams changes, only the order. Sorting is just choosing which column decides who comes first, and in which direction.
Watch it happen
Why numbers need a compare function
1/4Three prices in state: 10, 9 and 100. We want them low to high.
The big ideas
What you need to know
Field and direction
Every sort needs two things: which field (price, date) and which way (ascending or descending).
Paginated? Sort on the server
If you only have page 1, sorting it in the browser only sorts those 20 items, not the whole list.
sort() changes the array
Array.prototype.sort mutates in place. Copy first with [...items] or use toSorted().
Numbers need a compare function
Without one, sort compares as text, so 100 lands before 9.
See it in code
Walk through the code
1type SortKey = "price" | "rating";2type Dir = "asc" | "desc";3 4function sortProducts(items: Product[], key: SortKey, dir: Dir) {5 return [...items].sort((a, b) =>6 dir === "asc" ? a[key] - b[key] : b[key] - a[key]7 );8}9 10// Server-side version: let the API do it11fetch(`/api/products?sortBy=${key}&order=${dir}&page=1`);1/4Limit the sort choices to fields and directions that actually exist.
The spread makes a copy, so React state isn't mutated. For paginated data, send sortBy and order to the API instead.
Save yourself the pain
Common mistakes
Oops
Calling items.sort() directly on a state array.
Do this instead
Copy it first ([...items].sort(...)) so React sees a new array and re-renders.
Oops
Sorting only the current page of a paginated list.
Do this instead
Send the sort to the server so it sorts everything, then returns page 1.
Your mission
Add a sort dropdown
Quick check
What does [10, 9, 100].sort() return in JavaScript?
Go deeper
- 1Add a sortable table header that toggles ascending/descending on click.
- 2Sync the current sort field/direction to the URL.
- 3Handle sorting client-side vs server-side and know the trade-offs.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.