Vanilla JavaScript Projects

Project 73, E-commerce and business

Product Filter and Sort

The filter sidebar from every big shop, in one small file. Every choice updates the list instantly and the link, so a filtered page can be shared.

Main API
URLSearchParams
History
replaceState
Dependencies
None
Your browser
Checking

Filter the products

Tick categories, set a price range, pick colours and sort. Look at the address bar: the filters live there.

Category
Price ($)
Colour
Rating

How it works

  1. Filter, then sortEach product must pass every active filter. The survivors are sorted with one of five compare functions.
  2. The URL is the stateEvery change writes the filters to the address bar with URLSearchParams. Opening that link restores the same view.
  3. Chips for active filtersEach active filter becomes a small button above the results, and clicking it removes just that filter.
function run() {
  const s = readFilters();
  const list = products
    .filter((p) => (!s.cats.length || s.cats.includes(p.cat)) && p.price <= s.max && p.rating >= s.rating)
    .sort(sorters[s.sort]);
  const q = new URLSearchParams();
  s.cats.forEach((c) => q.append("cat", c));
  if (s.max !== Infinity) q.set("max", s.max);
  history.replaceState(null, "", "?" + q);
  render(list);
}