[Easy] LeetCode JS 30 - 2635. Apply Transform Over Each Element in Array

March 5, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2635. Apply Transform Over Each Element in Array

Question Prompt

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.

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

Start by defining a function map that takes two arguments: arr and fn . Then, create an empty array returnedArray to store the transformed elements.

Iterate through each element of the input array using for loop. In each iteration, applies the mapping function fn to the current element arr[i] and its index i, and stores the result at the corresponding index in the returnedArray.

Lastly, return the newly created array returnedArray containing the transformed elements

var map = function (arr, fn) {
  const returnedArray = [];
  for (let i = 0; i < arr.length; i++) {
    returnedArray[i] = fn(arr[i], i);
  }
  return returnedArray;
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee