Code Lab

Your own map

EasyFunctions5 min

Write a function map(arr, fn) without the built-in Array.prototype.map.

It returns a new array where each element is replaced by fn(arr[i], i). The callback fn gets the element and its index. Do not change the input array.

Examples

map([1, 2, 3], (n) => n + 1)

Returns [ 2, 3, 4 ]

map([10, 20, 30], (n, i) => n * i)

Returns [ 0, 20, 60 ]

The second argument of the callback is the index.

Source

Loading the editor...
  1. Adds 1 to each element
  2. Passes the index as the second argument
  3. An empty array gives an empty array

Hidden tests run on Submit.