We can create a custom map function that works like the native Array.prototype.map(). It takes a callback function, applies it to each element, and returns a new array.
1️⃣ Using a function on the prototype
// Custom map function
Array.prototype.myMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
// Example usage
const numbers = [1, 2, 3, 4];
const doubled = numbers.myMap((num) => num * 2);
console.log(doubled); // [2, 4, 6, 8]
Explanation:
thisrefers to the array on whichmyMapis calledcallback(this[i], i, this)passes:- Current element
- Index
- Original array
- Push result into a new array → ensures immutability
2️⃣ Using a standalone function (without modifying prototype)
function myMap(arr, callback) {
const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(callback(arr[i], i, arr));
}
return result;
}
// Example
const numbers = [5, 10, 15];
const squared = myMap(numbers, (n) => n * n);
console.log(squared); // [25, 100, 225]
⚡ Key Points:
- Always return a new array, do not mutate the original
- Callback receives value, index, and array like native
map() - Works with all array types