Module 22: Loops and Algorithms

Lesson 3 of 5 · 15–25 minutes

Searching

🏠The everyday picture

Finding a name in a pile of unsorted forms means checking every one. Finding it in a phone book, sorted alphabetically, means opening near the right letter and narrowing down.

📘What it really is

const byId = new Map(products.map(p => [p.id, p]));
byId.get("P003");

Getting an item from a Map is instant, however many items there are.

🖱️Try it

Write a function searchProducts(query) that returns every product whose name contains the query, ignoring case and extra spaces. Test it with "pen", " PEN " and "xyz". Then build a Map by id and look up two products.

✅Quick check

A search for "pen" misses "Pen Stand". What's the likely bug?

Show the answer

The comparison is case-sensitive. Convert both to lower case before comparing.

Why can binary search only be used on sorted data?

Show the answer

It relies on knowing which half the target must be in, which is only possible if the data is in order.

← PreviousTransforming data with map, filter and reduce
ProLearners Assist