Skip to curriculum
Jump to the editor

10.4. Array items reachable by index and by id

Medium
Topics
15–30 min

Records from an API usually arrive as an array: [{ id: "u1", name: "Ann" }, { id: "u2", name: "Ben" }]. Rendering wants them in order, by index; updates and lookups want them by id ("change u2"). Keeping a second object keyed by id means two structures to keep in sync. A Proxy can give one array both views: ask for an index and you get the item at that position, ask for an id and you get the record with that id.

Write createIdArray(items) in id-array.js. It wraps the array (without copying it) so that list[0] reads by index as usual and list.u2, or list["u2"], finds the item whose id is "u2".

Signature

JAVASCRIPT
function createIdArray(items) // returns the wrapped array
  • items: an array of objects, each with a string id. It is wrapped, not copied: a change made through the wrapper or to the original array shows in both.
  • Returns an array (Array.isArray is true) whose reads also understand ids.

Requirements

  1. Indexes work as on the plain array: list[0], list.length, and undefined past the end.
  2. Reading any other string key that the array does not have (as its own property or through Array.prototype) returns the first item whose id is exactly that key, or undefined if there is none.
  3. key in list is true for an id that some item has, and stays right for indexes, length and methods.
  4. Array indexes always win: list["1"] is the item at index 1, even if another item has the id "1", and list[9] past the end is undefined, never an id lookup.
  5. The array's own properties and methods win too: an item with the id "length" or "map" does not hide list.length or list.map.
  6. Lookups stay right after the array changes: after push, splice, replacing an item, or a change to the original array.
  7. Items that are null or not objects are skipped by the id lookup without an error.
  8. Everything else behaves like the plain array: map, filter, for...of, spread, Object.keys (indexes only) and JSON.stringify.

Examples

JAVASCRIPT
const users = createIdArray([
  { id: "u1", name: "Ann" },
  { id: "u2", name: "Ben" },
]);
users[0].name;       // "Ann"
users.u2.name;       // "Ben"
users["u3"];         // undefined
"u1" in users;       // true
users.length;        // 2
JAVASCRIPT
users.push({ id: "u3", name: "Cy" });
users.u3.name;                     // "Cy"
users.splice(0, 1);
users.u1;                          // undefined: removed
users.map((user) => user.name);    // ["Ben", "Cy"]
JAVASCRIPT
const odd = createIdArray([{ id: "1" }, { id: "x" }, { id: "length" }]);
odd["1"];           // { id: "x" }: index 1, not the item whose id is "1"
odd.length;         // 3, not the item with id "length"
odd[5];             // undefined: an index, never an id

Environment

  • Plain JavaScript in a browser page; the tests call the global createIdArray from id-array.js.
  • Use a Proxy. Writing by id (list.u2 = …) and deleting by id are not part of this problem.
  • An array index is a key like "0" or "15": a whole number from 0 to 2 ** 32 − 2 in its usual spelling. "01", "-1" and "1.5" are not indexes.

Hints

  1. Which two traps cover reading a property and the in operator?
  2. If you build an id-to-item map once, what happens to it when someone calls push?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…