What's your approach to implementing a map() function in JavaScript, where each array element is transformed by a specified callback?
Question Analysis
The question is asking you to implement a custom map()
function in JavaScript. The map()
function is a higher-order function that applies a given callback function to each element of an array, producing a new array with the transformed elements. This is a fundamental concept in functional programming and is commonly used in JavaScript for array manipulation.
Key points to consider:
- Input: An array and a callback function.
- Output: A new array where each element is the result of applying the callback function to the corresponding element of the input array.
- Characteristics: The original array should not be modified, and the transformation should be applied in sequence.
Answer
To implement a custom map()
function in JavaScript, you can define a function that iterates over each element of the input array, applies the callback function to transform the element, and stores the result in a new array. Here is a sample implementation:
function customMap(array, callback) {
// Create a new array to hold the transformed elements
let resultArray = [];
// Iterate over each element in the input array
for (let i = 0; i < array.length; i++) {
// Apply the callback function to the element and store the result
resultArray.push(callback(array[i], i, array));
}
// Return the new array with transformed elements
return resultArray;
}
// Example usage:
const numbers = [1, 2, 3, 4, 5];
const doubled = customMap(numbers, function(num) {
return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]
Explanation:
- Function Definition: The
customMap
function takes two arguments:array
andcallback
. - Result Array: A new, empty array
resultArray
is initialized to store the transformed elements. - Iteration: A
for
loop iterates through each element of the input array. - Callback Application: The
callback
is called with the current element, index, and the original array as arguments. The result is pushed intoresultArray
. - Return: The function returns
resultArray
, which contains the transformed elements.
This implementation mirrors the behavior of the native Array.prototype.map()
method in JavaScript, ensuring that each element is processed and transformed correctly without altering the original array.