AniUI Academy

Normalise a list into a lookup object

easyArrays & Objects+150 XPPractice

State libraries normalise data for a reason: with a thousand rows on screen, calling rows.find(r => r.id === id) on every render is a thousand comparisons per lookup. An object keyed by id makes it one.

Implement indexBy(items, key). items is an array of objects and key is the name of the property to index by. Return a plain object mapping each item's value at that property to the item itself. Because these become object properties, the values are coerced to strings, so an item with id: 1 is stored under "1". Items that do not have key as an own property are skipped. When two items share the same key value, the later one wins. An empty input array returns an empty object. Never modify the items or the array.

Arguments

itemsArray<Object>
The records to index. Each item is stored under its own value at key.
keystring
The property name to index by. Items missing this own property are skipped.

Returns

Object<string, Object> — A lookup object mapping each item's key value (coerced to a string) to the item itself.

Examples

indexBy([{ id: "a", n: 1 }, { id: "b", n: 2 }], "id");
// { a: { id: "a", n: 1 }, b: { id: "b", n: 2 } }
indexBy([{ id: 1, v: "x" }, { id: 1, v: "y" }], "id");
// { "1": { id: 1, v: "y" } } — the later item wins on a duplicate key

What it has to do

  • Map each item's key value to the item object itself.
  • Coerce key values to strings, since they become object properties.
  • Skip items that lack the key as an own property.
  • Let the later item win when two share a key value.
  • Return {} for an empty input array, and do not mutate the input.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.