Hiprup

How do you implement Array.map from scratch?

map builds a new array by transforming each element.

  1. Create an empty result array.

  2. Loop the original by index.

  3. Push callback(element, index, array) for each item.

  4. Return the new array; the original is unchanged.

Non-mutating: and the callback receives the index and full array too.

Array.prototype.myMap = function(callback, thisArg) {
  const result = new Array(this.length);
  for (let i = 0; i < this.length; i++) {
    if (i in this) { // Handle sparse arrays
      result[i] = callback.call(thisArg, this[i], i, this);
    }
  }
  return result;
};

// Test
console.log([1, 2, 3].myMap(x => x * 2));       // [2, 4, 6]
console.log([1, 2, 3].myMap((x, i) => x + i));  // [1, 3, 5]
console.log(['a', 'b'].myMap(s => s.toUpperCase())); // ['A', 'B']

Creates result array of same length. For each element, calls callback with (element, index, array) and stores the return value. callback.call(thisArg, ...) preserves this context.

Sparse array check (i in this) skips holes. Returns a new array — original unchanged.

Key details: new array same length, callback gets (element, index, array), callback.call for this binding, i in this for sparse arrays. Never mutate the original.

This is a common coding interview question.