JS Built-ins
← Array117 / 226
ArrayArray.prototype.keysbeginner

Array.prototype.keys() β€” convert iterator to array

πŸ“– Usage Example
const arr = ['a', 'b', 'c']
const keys = arr.keys()
keys.next().value  // β†’ 0
keys.next().value  // β†’ 1

Use keys() to get an iterator that yields the index of each element.

Array.prototype.keys()

Array.prototype.keys() returns an Array Iterator that yields the index of each element. Because it returns an iterator (not a plain array), you need to convert it with Array.from() or the spread operator to get an actual array.

Challenge: Implement getKeys(arr) that converts arr.keys() to an array of indices.

getKeys(['a', 'b', 'c']) // β†’ [0, 1, 2]
getKeys([])              // β†’ []
πŸ’‘ Hints (2)
  • β€’ `arr.keys()` returns an iterator, not an array β€” wrap it with `Array.from()`.
  • β€’ You can also use the spread operator: `[...arr.keys()]`.