Implementing your version of popular JavaScript functions is a fairly trivial interview question, so to prepare for it, I decided to implement all of them on my own as a part of the interview process. Array.map()
is a starting point in the series. The next ones in the queue are Array.filter()
and Array.reduce()
.
Array.map()
?To begin with, let’s first figure out what Array.map()
is. Array.map()
is a built-in JavaScript function for array manipulations and transformations based on the existing array. Array.map()
iterates each element of the existing array and applies a callback function for each element. Array.map()
doesn't mutate the original array. Instead, it returns a new one.
1const arr = [1, 2, 3];2
3const doubled = arr.map((elem) => elem * 2);4
5console.log(doubled);6// Output: [2, 4, 6]
Array.map()
Now, let’s implement myMap()
function, which will act as your Array.map()
replacement.
The myMap()
function takes an arr
(array) and a cb
(callback) function as arguments. It returns a new array that results from applying the callback function to each input array element.
1const myMap = (arr, cb) => {2 let temp = [];3
4 for (let i = 0; i < arr.length; i++) {5 if (arr.hasOwnProperty(i)) {6 temp.push(cb(arr[i]));7 }8 }9
10 return temp;11};
Let’s quickly go through the code to figure out what it does.
We start by creating a new empty array temp
1let temp = [];
Then we loop through each element of the input array arr
1for (let i = 0; i < arr.length; i++) {2 // loop code3}
We do `hasOwnProperty`` check ensures that the callback is only executed on elements that actually exist in the array, and it won't be invoked for undefined elements or holes in the array.
1if (arr.hasOwnProperty(i)) {2 ...3}
Inside the loop, it applies the callback function cb
to the current element of the input array arr[i]
. Finally, the result is pushed into a temporary array temp
.
1temp.push(cb(arr[i]));
After we finish with the loop, we return the temp
array.
1return temp;
That's it! Now you can use myMap()
as an alternative replacement to the existing Array.map()
function.
1const arr = [1, 2, 3];2
3const doubled = myMap(arr, (elem) => elem * 2);4
5console.log(doubled);6// Output: [2, 4, 6]
Sign up to get updates when I write something new. No spam ever.
Subscribe to my Newsletter