JS Built-ins
← Array121 / 226
ArrayArray.prototype.keysadvanced

Array.prototype.keys() β€” build an index map

πŸ“– Usage Example
const arr = ['a', 'b']
[...arr.keys()]     // β†’ [0, 1]           (indices only)
[...arr.entries()]  // β†’ [[0,'a'],[1,'b']] (index+value pairs)

Use keys() for indices only; use entries() when you need both the index and the value.

Array.prototype.keys() β€” index map

keys() gives you just the indices, while entries() gives you [index, value] pairs. When you only need the indices to look up values manually, keys() is the right choice.

Challenge: Implement indexMap(arr) that returns an object mapping each numeric index to its corresponding array value.

indexMap(['a', 'b', 'c']) // β†’ { 0: 'a', 1: 'b', 2: 'c' }
indexMap([])              // β†’ {}
πŸ’‘ Hints (3)
  • β€’ Use `for (const i of arr.keys())` to get each index.
  • β€’ Assign `result[i] = arr[i]` inside the loop to populate the map.
  • β€’ `keys()` only yields indices β€” you still need `arr[i]` to get the value.