Problem : Apply Transform Over Each Element in Array | #2635 | LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element.
The returned array should be created such that returnedArray[i] = fn(arr[i], i).
Please solve it without the built-in `Array.map` method.
Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output: [2,3,4]
Explanation:
const newArray = map(arr, plusone); // [2,3,4]
The function increases each value in the array by one.
Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output: [1,3,5]
Explanation:
The function increases each value by the index it resides in.
Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]
Explanation: The function always returns 42.
/**
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var map = function(arr, fn) {
returnedArray = []
for (let i =0; i<arr.length; i++){
returnedArray[i] = fn(arr[i], i)
}
return returnedArray
};
This code defines a JavaScript function called `map` that mimics the behaviour of the built-in `Array.prototype.map()` method. The `map` function takes two arguments: an array (`arr`) and a callback function (`fn`). It applies the callback function to each element of the input array and returns a new array containing the results of those function calls.
Here's a step-by-step explanation of the code:
1. Function Definition:
a. The `map` function is defined with two parameters: `arr` (an array) and `fn` (a callback function).
2. Initialise an Empty Array:
a. Inside the `map` function, an empty array called `returnedArray` is initialised. This array will store the results of applying the callback function to each element of the input array.
3. Loop Over the Input Array:
a. A `for` loop is used to iterate through each element of the input array, `arr`. The loop variable `i` is initialised to 0.
b. The loop continues as long as `i` is less than the length of the input array (`arr.length`).
4. Apply the Callback Function:
a. Inside the loop, the callback function `fn` is called with two arguments:
b. The current element of the input array (`arr[i]`).
c. The index of the current element (`i`).
d. The result of calling the callback function is stored in the `returnedArray` at the same index, `i`.
5. Return the New Array:
a. After the loop completes, the `map` function returns the `returnedArray`, which now contains the results of applying the callback function to each element of the input array.