Skip to the solution
MediumDSAAsked in 20245 min read

Index By Utility

3.2k views

The problem

Problem, as an interviewer would state it: "Implement indexBy(array, key) — converting an array into an object keyed by a property (or by a function's result) for O(1) lookup, with sensible handling for duplicate keys and for hostile keys such as __proto__."

Examples:

Code
indexBy([{ id: 1, n: "a" }, { id: 2, n: "b" }], "id");
// { 1: { id: 1, n: "a" }, 2: { id: 2, n: "b" } }

Clarifying questions expected:

  • When two items produce the same key, should the first or last win — or should it be an error?
  • Is the key property guaranteed to be safe, or could it come from untrusted data?
  • Should a function be accepted as well as a property name?

Code / implementation expected: Yes — real, direct proof of each collision mode and of the prototype-safety behavior.

  • array
  • object

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: indexBy collision modes work, and a __proto__ key is safe on a null-prototype result but hijacks the prototype of a plain object result

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 59 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Build an Async Priority Task Scheduler

Continue