JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 15: Interactive Application ArchitectureLesson 74 of 150About 50 minutes

Lesson 74: Filtering, searching and pagination

01Opening question

A catalogue has 240 products. How do people find the six they care about?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Search and pagination are just array functions: filter the full list, then slice out one page.

const products = ["Desk lamp", "Floor lamp", "Mug", "Lamp shade", "Desk"];
const search = (list, q) => list.filter((p) => p.toLowerCase().includes(q.trim().toLowerCase()));
const page = (list, n, size) => list.slice((n - 1) * size, n * size);
const found = search(products, "lamp");
console.log(found.length, page(found, 1, 2), page(found, 2, 2));

03Objective and prerequisites

Learning objective: Implement search, filters, sorting and pagination as pure functions over state, and render the visible page with counts and accessible controls.

You need: Lesson 73: State-driven rendering, Lesson 33: filter and selection

Skills practised: Browser application architecture, Search, filter and pagination.

04Explanation

Search keeps items whose text includes the query, usually ignoring case and surrounding spaces.

Filters keep items matching chosen options (category, price range). Sorting orders the result.

Pagination shows one slice at a time: page n of size s is list.slice((n - 1) s, n s). The number of pages is Math.ceil(total / s).

Keep the query, filters, sort and page number in state, and compute the visible items from the full list every time.

05Definitions

Search
Keeping only items whose text matches a query.
Filter
Keeping only items that match chosen criteria, such as a category.
Pagination
Splitting a long list into pages and showing one page at a time.
Page count
The number of pages, Math.ceil(total / pageSize).
aria-current
An attribute marking the current item in a set, such as the current page link.

Open the full glossary

06Visual learning object

Search and filter interface. Type a query, pick filters and change pages on a sample catalogue, and see each step of the pipeline: all, searched, filtered, sorted, paged.

Loading the interactive object…

Open the full Search and filter interface page with its guided experiment.

07Examples

ex-074-01The search → filter → sort → page pipeline Browser page (sandboxed preview)

Each step is a small pure function; together they compute the view.

const products = [
  { name: "Desk lamp", cat: "lighting", price: 35 },
  { name: "Floor lamp", cat: "lighting", price: 80 },
  { name: "Oak desk", cat: "furniture", price: 220 },
  { name: "Lamp shade", cat: "lighting", price: 15 },
  { name: "Desk mat", cat: "office", price: 20 }
];
const bySearch = (list, q) => list.filter((p) => p.name.toLowerCase().includes(q.trim().toLowerCase()));
const byCat = (list, cat) => (cat === "all" ? list : list.filter((p) => p.cat === cat));
const byPrice = (list) => [...list].sort((a, b) => a.price - b.price);
const paginate = (list, page, size) => list.slice((page - 1) * size, page * size);
const state = { q: "lamp", cat: "lighting", page: 1, size: 2 };
const results = byPrice(byCat(bySearch(products, state.q), state.cat));
console.log(results.length, Math.ceil(results.length / state.size));
console.log(paginate(results, state.page, state.size).map((p) => p.name).join(", "));
Sample input
None
Expected output
3 2 Lamp shade, Desk lamp
Common mistake
Paginating before filtering, so page 1 shows only the matches that happened to be in the first slice.
Try this
Add a maximum price filter.
Source
examples/ex-074-01-pipeline.js

ex-074-02Rendering live search results Browser page (sandboxed preview)

State holds the query; render shows the matches and a count.

const cities = ["Toronto", "Tokyo", "Lima", "Tallinn", "Oslo"];
const state = { q: "" };
function render() {
  const q = state.q.trim().toLowerCase();
  const matches = cities.filter((c) => c.toLowerCase().includes(q));
  document.querySelector("#count").textContent = matches.length ? matches.length + " results" : "No results";
  document.querySelector("#results").replaceChildren(...matches.map((c) => Object.assign(document.createElement("li"), { textContent: c })));
}
const input = document.querySelector("#q");
input.addEventListener("input", () => { state.q = input.value; render(); });
render();
for (const text of ["to", "xyz"]) {
  input.value = text;
  input.dispatchEvent(new Event("input"));
  console.log(document.querySelector("#count").textContent, document.querySelector("#results").textContent);
}
Sample input
None
Expected output
2 results TorontoTokyo No results
Common mistake
Showing an empty list with no message when nothing matches.
Try this
Highlight the matching part of each city name with a mark element.
Source
examples/ex-074-02-live-search.js

ex-074-03A pager component Browser page (sandboxed preview)

Previous/Next buttons and page numbers, with the current page marked.

function Pager({ page, pages, onChange }) {
  const nav = document.createElement("div");
  const button = (label, target, disabled) => {
    const b = document.createElement("button");
    b.type = "button";
    b.textContent = label;
    b.disabled = disabled;
    if (label === String(page)) b.setAttribute("aria-current", "page");
    b.addEventListener("click", () => onChange(target));
    return b;
  };
  nav.append(button("Prev", page - 1, page === 1));
  for (let p = 1; p <= pages; p++) nav.append(button(String(p), p, false));
  nav.append(button("Next", page + 1, page === pages));
  return nav;
}
let page = 1;
function render() {
  document.querySelector("#pager").replaceChildren(Pager({ page, pages: 3, onChange: (p) => { page = p; render(); } }));
}
render();
const next = () => [...document.querySelectorAll("#pager button")].find((b) => b.textContent === "Next");
next().click();
next().click();
console.log(page, next().disabled, document.querySelector('[aria-current="page"]').textContent);
Sample input
None
Expected output
3 true 3
Common mistake
Letting Next go past the last page and rendering an empty list.
Try this
Show at most five page numbers with ellipses.
Source
examples/ex-074-03-pager.js

ex-074-04Reset to page 1 when filters change Browser page (sandboxed preview)

Changing the query keeps the page valid.

const items = Array.from({ length: 23 }, (_, i) => "Item " + (i + 1));
const state = { q: "", page: 3, size: 10 };
const visible = (s) => {
  const found = items.filter((x) => x.includes(s.q));
  const pages = Math.max(1, Math.ceil(found.length / s.size));
  const page = Math.min(s.page, pages);
  return { found: found.length, pages, page, shown: found.slice((page - 1) * s.size, page * s.size) };
};
console.log(JSON.stringify(visible(state)).length > 0, visible(state).shown.length);
const setQuery = (q) => { state.q = q; state.page = 1; };
setQuery("2");
const v = visible(state);
console.log(v.found, v.pages, v.page, v.shown.slice(0, 3).join(", "));
Sample input
None
Expected output
true 3 6 1 1 Item 2, Item 12, Item 20
Common mistake
Keeping page 3 after a search that only has one page of results.
Try this
Also clamp the page when items are deleted.
Source
examples/ex-074-04-reset-page.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Page 1 skips the first items

Compute slice bounds correctly.

const items = ["a", "b", "c", "d", "e"];
function getPage(list, page, size) {
  return list.slice(page * size, page * size + size);
}
console.log(getPage(items, 1, 2).join(","));

Filter and sort books

Combine search, filter and sort without mutating.

const books = [
  { title: "Dune", year: 1965, genre: "sci-fi" },
  { title: "Emma", year: 1815, genre: "classic" },
  { title: "Neuromancer", year: 1984, genre: "sci-fi" },
  { title: "Dracula", year: 1897, genre: "classic" }
];
function query(list, { q = "", genre = "all", sort = "title" }) {
  // TODO: search titles (case-insensitive), filter by genre unless "all",
  // sort by "title" (A-Z) or "year" (oldest first) on a copy
}
console.log(query(books, { genre: "sci-fi", sort: "year" }).map((b) => b.title).join(", "));
console.log(query(books, { q: "d" }).map((b) => b.title).join(", "));

A searchable, paged list

Build state, a pipeline and a render with counts.

const names = ["Ada", "Alan", "Grace", "Linus", "Margaret", "Barbara", "Ken", "Dennis", "Anita", "Radia"];
// state = { q: "", page: 1 }, page size 3.
// render(): search names (case-insensitive), clamp page, show the page in
//   #list, #status "Page P of N (T results)", disable Prev/Next at the ends.
// Typing in #q sets q and resets page to 1. Prev/Next change page.
// Click Next twice, then type "a" and click Next once; log #status.

09Prediction

Commit to an answer first, then run the real code to compare.

const n = 23, size = 10;
console.log(Math.ceil(n / size), Math.floor(n / size), n % size);

What is printed?

10Debugging investigation

Search shows "no results" although there are matches

On page 3 of all products, searching for "lamp" shows an empty list, although two lamps exist.

const products = ["Desk lamp", "Mug", "Chair", "Floor lamp", "Rug", "Vase", "Clock"];
const state = { q: "", page: 3, size: 3 };
function render() {
  const found = products.filter((p) => p.toLowerCase().includes(state.q.toLowerCase()));
  const shown = found.slice((state.page - 1) * state.size, state.page * state.size);
  document.getElementById("list").replaceChildren(...shown.map((p) => Object.assign(document.createElement("li"), { textContent: p })));
  document.getElementById("status").textContent = shown.length + " shown";
}
const q = document.getElementById("q");
q.addEventListener("input", () => {
  state.q = q.value;
  render();
});
q.value = "lamp";
q.dispatchEvent(new Event("input"));
console.log(document.getElementById("status").textContent);

More cases in the Debugging Detective Laboratory

11Practical scenario

Catalogue search that can be shared

An online store keeps the search box, category filter and page number in the URL (?q=lamp&cat=lighting&page=2). Reloading or sharing the link shows exactly the same results, because the page rebuilds its state from the URL and runs the same search, filter and pagination functions.

const params = new URLSearchParams("q=lamp&cat=lighting&page=2");
console.log(params.get("q"), params.get("cat"), Number(params.get("page")));

12Knowledge check

1. Which expression gives page n (from 1) of size s?

  • list.slice(n s, n s + s)
  • list.slice((n - 1) s, n s)
  • list.slice(n, s)
  • list.splice((n - 1) * s, s)

2. How many pages do 21 items need at 5 per page?

  • 4
  • 5
  • 4.2
  • 6

3. What should happen to the page number when the search query changes?

  • Stay the same
  • Reset to 1
  • Go to the last page
  • Become 0

4. Why is the original product list reordered after sorting results?

const results = products.sort((a, b) => a.price - b.price);
  • sort sorts the array in place
  • filter reorders
  • slice changes the original
  • map sorts

5. In what order should the steps run?

  • page → sort → filter → search
  • search → filter → sort → page
  • sort → page → search
  • Any order

6. How should the result count be shown?

  • Only in the page title
  • In a status live region near the results
  • In the console
  • Not at all

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Page 1 skips the first items: Prints a,b; Last page is partial
  • Filter and sort books: Prints both queries; Does not reorder the source; No matches gives []
  • A searchable, paged list: Prints the status; No results

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-15-interactive-application-architecture/lesson-074-filtering-searching-and-pagination/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Search, filter, sort and paginate with small pure functions.
  • Run them in order: search → filter → sort → page.
  • Reset to page 1 when the query changes and clamp the page.
  • Show counts and empty states, and mark the current page accessibly.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation filtering, searching and pagination
Context: I am learning filtering, searching and pagination in JavaScript.
Task: Explain a search, filter, sort and pagination pipeline with a product list.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction filtering, searching and pagination drill
Context: I have practised filtering, searching and pagination.
Task: Give me six pipeline questions with lists, queries and page sizes, and ask what is shown.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging filtering, searching and pagination bug
Context: After searching, my list is empty although there are matches.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation filtering, searching and pagination practice
Context: I finished the filtering, searching and pagination exercises.
Task: Create three exercises that build search, filters and pagination with exact expected output.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review filtering, searching and pagination review
Context: Here is my code that uses filtering, searching and pagination.
Task: Review my list code for in-place sorting, missing page resets and empty states.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.