Day 5: Apply Transform Over Each Element in Array — 30 days of LeetCode challenge.
Problem
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.
Example 1
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.
Example 2
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.
Example 3
Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]
Explanation: The function always returns 42.
Constraints
0 <= arr.length <= 1000
-10<sup>9</sup> <= arr[i] <= 10<sup>9</sup>
fn
returns a number
Solution
* @param {number[]} arr
* @param {Function} fn
* @return {number[]}
*/
var map = function(arr, fn) {
let newArray = []
for(i= 0; i< arr.length; i++){
newArray[i] = fn(arr[i] ,i)
}
return newArray
};
Explanation
In the code above, we have a function map
that takes two argument arr
and fn
. fn
is a callback function that is applied to each element in the array.
We created an empty array newArray
The for loop
is used to iterate over each element in the array and increment it by 1. i
stands for the index variable.
newArray[i] = fn(arr[i], i )
In this logic, we assigned a callback function fn
to the newArray[i]. The callback function gets invoked using the current element arr[i]
and the current index i
.
Each element in the array gets transformed by the callback function fn
and is stored in the corresponding index of newArray
.
Conclusion
In this article, we have solved the Apply Transform Over Each Element in Array Leettcode challenge.
Looking forward to solving the next challenge
Subscribe to my newsletter
Read articles from Susan Odii directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Susan Odii
Susan Odii
Susan is a Frontend Web Developer. She is passionate about creating beautiful and engaging UI with good user experience. Susan is also a technical writer who writes on Frontend technologies to help other developers get a better understanding of a concept.