JS Built-ins
← Array135 / 226
ArrayArray.prototype.mapintermediate

Array.prototype.map() β€” use the index parameter

πŸ“– Usage Example
const letters = ['a', 'b', 'c']
letters.map((v, i) => i + ':' + v)
// β†’ ['0:a', '1:b', '2:c']

Use the index parameter of map() to include positional information in the transformed output.

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

The map callback optionally receives a second argument: the current element's index. This is useful for labelling, numbering, or interleaving positional data.

Challenge: Implement addIndex(arr) that prepends each element's index to its value.

addIndex(['a', 'b', 'c']) // β†’ ['0: a', '1: b', '2: c']
addIndex([])              // β†’ []
πŸ’‘ Hints (2)
  • β€’ The second parameter of the `map` callback is the index: `(s, i) => ...`.
  • β€’ Use a template literal: `` `${i}: ${s}` ``.