Skip to the content

Lesson 76 of 296

Your own map, filter and reduce

On this page

The task

"Implement Array.prototype.map, filter and reduce yourself, without using the built-in versions."

What the interviewer is checking

  • That you understand what each method really does (Lesson 60).
  • That you know this inside a method is the array (Lesson 55).
  • Edge cases: the optional thisArg, a missing callback, and reduce with no starting value.

Questions to ask first

  • "Should I add them to Array.prototype, or write normal functions that take the array as an argument?"
  • "Do you want me to handle sparse arrays (arrays with holes) like the built-ins?"

Asking shows you think about requirements before coding. If they say "your choice", adding to the prototype with a different name (myMap) is the usual answer.

Step 1: map

Rules of the real map:

  • Calls the callback with (item, index, array).
  • Returns a new array of the same length.
  • Uses the optional second argument as this inside the callback.
  • Skips holes in sparse arrays, keeping them as holes.
Array.prototype.myMap = function (callback, thisArg) {
  if (typeof callback !== "function") {
    throw new TypeError(callback + " is not a function");
  }
  const result = new Array(this.length);
  for (let i = 0; i < this.length; i++) {
    if (i in this) {
      result[i] = callback.call(thisArg, this[i], i, this);
    }
  }
  return result;
};

Line by line:

  • function, not an arrow function, because we need this to be the array.
  • new Array(this.length) creates an array of the right length.
  • i in this is false for holes, so holes stay holes. (For normal arrays it is always true.)
  • callback.call(thisArg, ...) runs the callback with the chosen this.

Step 2: filter

Array.prototype.myFilter = function (callback, thisArg) {
  if (typeof callback !== "function") {
    throw new TypeError(callback + " is not a function");
  }
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (i in this && callback.call(thisArg, this[i], i, this)) {
      result.push(this[i]);
    }
  }
  return result;
};

The only difference from map: we push the original item when the callback returns something truthy.

Step 3: reduce

reduce is the tricky one, because of the optional starting value:

  • With a starting value: the accumulator starts as that value, and the loop starts at index 0.
  • Without one: the accumulator starts as the first item, and the loop starts at index 1.
  • Without one, on an empty array: throw a TypeError.

How do we know if a starting value was passed? We cannot check initialValue === undefined, because someone might really pass undefined as the start. So we use a rest parameter and check its length.

Array.prototype.myReduce = function (callback, ...rest) {
  if (typeof callback !== "function") {
    throw new TypeError(callback + " is not a function");
  }
  let i = 0;
  let acc;

  if (rest.length > 0) {
    acc = rest[0];
  } else {
    while (i < this.length && !(i in this)) i++;
    if (i >= this.length) {
      throw new TypeError("Reduce of empty array with no initial value");
    }
    acc = this[i];
    i++;
  }

  for (; i < this.length; i++) {
    if (i in this) {
      acc = callback(acc, this[i], i, this);
    }
  }
  return acc;
};

Test it

[1, 2, 3].myMap((n) => n * 2)                 [2, 4, 6]
[1, 2, 3, 4].myFilter((n) => n % 2 === 0)     [2, 4]
[1, 2, 3].myReduce((a, b) => a + b, 0)        6
[1, 2, 3].myReduce((a, b) => a + b)           6
[].myReduce((a, b) => a + b, 5)               5
[].myReduce((a, b) => a + b)                  TypeError

Cost

TimeExtra memory
mapO(n)O(n) for the new array
filterO(n)Up to O(n)
reduceO(n)O(1), plus whatever the accumulator holds

O(n) means "grows in step with the number of items". Part 10 explains this notation.

Follow-up questions

  • "Why not an arrow function?" Arrow functions have no own this, so this would not be the array.
  • "Is adding to Array.prototype a good idea in real code?" No. It can clash with future built-ins and other libraries. It is fine for practice.
  • "How would you write map using reduce?"
const mapWithReduce = (arr, fn) =>
  arr.reduce((acc, item, i) => {
    acc.push(fn(item, i, arr));
    return acc;
  }, []);

Common mistakes

  • Arrow functions for the methods.
  • Changing the original array.
  • Checking initialValue === undefined instead of whether it was passed.
  • Forgetting the index and array arguments to the callback.

How to say it in an interview

"I add them as regular functions on Array.prototype so this is the array. map builds a new array of the same length with the callback's results, filter pushes the original items where the callback is truthy, and both accept a thisArg. For reduce I check whether an initial value was passed using the argument count, not undefined; without one I start from the first element and throw a TypeError on an empty array. All three are linear time."

Key words

WordMeaning
PolyfillYour own code that copies a built-in feature, often for older environments
thisArgThe optional value used as this inside the callback
Sparse arrayAn array with empty slots (holes)
AccumulatorThe running result in reduce

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.