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.
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 keyWhat 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.
- 1.keys each item by the named property
- 2.lets the later item win on a duplicate key
- 3.skips items missing the key
- 4.returns an empty object for empty input
- 5.does not mutate the input items
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.