Before this lesson

Understand variables, types and loops, and distinguish strings from arrays.

What you will be able to do

Express data processing with filtering, mapping and lookup while separating display formatting from stored data.

Understand the mechanism

Strings are immutable; trim, toLowerCase and replace return new strings. length counts UTF-16 code units, not always visible characters. Normalize both query and target before case-insensitive matching; use localeCompare for locale-aware comparison.

filter selects entries, map transforms them, and find returns a first match or undefined. These methods do not directly change the source array structure, but callbacks can mutate shared objects. sort mutates its array; copy before sorting to preserve the original order.

Arrays model ordered collections; objects model named fields; Set deduplicates primitive values; Map supports keyed lookup. Titles can change or collide, so use stable IDs to identify records across filtering, sorting and deletion.

Runnable example

const lessons = [
  { id: 1, title: "HTML basics", minutes: 20 },
  { id: 2, title: "CSS layout", minutes: 35 },
  { id: 3, title: "HTML forms", minutes: 25 }
];
const query = " html ".trim().toLowerCase();
const result = lessons
  .filter(item => item.title.toLowerCase().includes(query))
  .map(item => ({ ...item, label: `${item.title} · ${item.minutes} min` }));
const ordered = [...result].sort((a, b) => b.minutes - a.minutes);
console.table(ordered);
console.log(lessons.map(item => item.id));

Trace and verify

Expect HTML forms before HTML basics, while original IDs remain 1, 2, 3. An unknown query gives an empty array. includes with an empty query is true, so an empty search displays everything.

Common mistakes and boundaries

Default sort compares strings; provide a comparator for numbers. Check a find result before reading properties. Regular expressions help with patterns, but simple substring search should not build dynamic expressions whose special characters change behavior.

Practice challenge

Calculate total study time for search results, returning zero for no matches. Add two courses sharing a title but having different IDs and ensure both remain.

Reference solution and reasoning

An initial reduce value of zero defines the empty case. Deduplication is a product rule; identical titles alone should not discard records.

const total = result.reduce((sum, item) => sum + item.minutes, 0);
console.log(total);

Further reading