Lessons · TypeScript · array or Map?
Array or object?
An array is for things in order, reached by position; an object or Map is for things with a name, reached by key.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Searching an array for a user by id on every render is the front-end's most common slow path. Keying by id makes lookups instant.
How to think about it
How will I get things OUT: by position or by id? Ask how you get things OUT: 'the next one', 'in order': array. 'The one with this id': object or Map. Often you keep both: an array of ids for order and a map of id to record.
Worked example
const order = ["u2", "u1"];Display order.
const byId = { u1: {name: "Ada"}, u2: {name: "Bo"} };Lookup by id.order.map(id => byId[id].name)["Bo", "Ada"]: order from the array, data from the object.
Your turn
Index records by id.
const byId = {};
for (const r of records) byId[r.] = r;Solve one with the tests running
The trap
Using an array's index as an id. Delete one item and every id after it changes.
Practise array or Map? on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.