Lesson 6 of 8

Fast lookup by ID

Goal

Build the index once, then look up in one step

01

Explanation

Each order has a user ID, and you want that user's name. If you write users.find(u => u.id === order.userId) inside the loop over the orders, the code walks the whole user list for every single order, and four thousand orders with four thousand users means millions of comparisons.

The fix is to build an index once with new Map(users.map(u => [u.id, u])), so every lookup with get takes a single step no matter how long the list is. The same goes for the question "is this in the list?": instead of includes inside the loop, use a Set with has.

Watch out: a Map takes the key's type into account, so get('7') won't find the key 7. IDs that come from dataset or from the URL are always strings, so convert them to numbers with Number before you look them up.

02

Your task

Rewrite withNames(orders, users) to use a Map index and withoutBlocked(orders, blockedIds) to use a Set, so the results stay the same and each list is read only once. If an order's user isn't in the user list, set the name to 'Unknown', just like the current code does.

Checks

5 checks
  1. withNames adds the right name
  2. A missing user gets the name "Unknown"
  3. The user list is read once, not for every order
  4. withoutBlocked drops the orders of blocked users
  5. The block list is read once, not for every order
03

Hints

0/3
Track lessons0 of 8 done

Find out where your page really loses time, and how to win it back by adding elements in one go, making fewer calls and never computing the same thing twice.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.

Track lessons0 of 8 done

Find out where your page really loses time, and how to win it back by adding elements in one go, making fewer calls and never computing the same thing twice.

Advanced level, 8 lessons, 1.5 hours in total.