JS Built-ins
← Array12 / 226
ArrayArray.frombeginner

Array.from() β€” create an index array

πŸ“– Usage Example
Array.from({length: 3}, (_, i) => i)
// β†’ [0, 1, 2]

Use Array.from() with an array-like object and a map function to generate index arrays.

Array.from() β€” length-object + map

Array.from() accepts any array-like object β€” including plain objects with a length property. Combined with the optional mapping function (second argument), you can generate sequences without a loop.

This pattern mirrors how Array.from(nodeList) works in the browser to convert a DOM NodeList into a real array.

Challenge: Implement createIndexArray that returns [0, 1, 2, …, n-1] using Array.from({ length: n }, (_, i) => i).

createIndexArray(3) // β†’ [0, 1, 2]
createIndexArray(0) // β†’ []
πŸ’‘ Hints (2)
  • β€’ `{ length: n }` is an array-like object β€” `Array.from` treats it like a sparse array.
  • β€’ The mapping function receives `(value, index)` β€” use the index to produce the sequence.