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
thisinside a method is the array (Lesson 55). - Edge cases: the optional
thisArg, a missing callback, andreducewith 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
thisinside 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 needthisto be the array.new Array(this.length)creates an array of the right length.i in thisis false for holes, so holes stay holes. (For normal arrays it is always true.)callback.call(thisArg, ...)runs the callback with the chosenthis.
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) TypeErrorCost
| Time | Extra memory | |
|---|---|---|
| map | O(n) | O(n) for the new array |
| filter | O(n) | Up to O(n) |
| reduce | O(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, sothiswould not be the array. - "Is adding to
Array.prototypea 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
mapusingreduce?"
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 === undefinedinstead 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
| Word | Meaning |
|---|---|
| Polyfill | Your own code that copies a built-in feature, often for older environments |
| thisArg | The optional value used as this inside the callback |
| Sparse array | An array with empty slots (holes) |
| Accumulator | The running result in reduce |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.