Normalise a list into a lookup object
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.
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.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.