LeetCode Problem 2635 Apply Transform Over Each Element in Array — LeetCode: 30 Days of JavaScript

LeetCode Problem 2635 Apply Transform Over Each Element in Array — LeetCode: 30 Days of JavaScript

I’ve been going through the 30 Days of Javascript in LeetCode. Right now, I’m on 2635. Apply Transform Over Each Element in Array.

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.

First Attempt:

When I first encountered the problem, I overthought it, which ended up consuming nearly the entire day.

let fn = function (arr, i = 0) {
  return i + arr;
};

var map = function (arr, fn) {
  let returnedArray = [];
  for (let i = 0; i < arr.length; i++) {
    returnedArray[i] = fn(arr[i], 1);
  }
  return returnedArray;
};

In my first attempt, this is what I did:

  1. I began by defining a function (transformation function) called fn. It takes the parameters arr and i, which is set to 0 if not defined. The function returns the result of adding each item in arr with i.

  2. Next, I created another function called map, which takes arr and the previously defined fn as parameters. I initialized an empty array called returnedArray to store the transformed values.

  3. I then set up a for loop to iterate through each value in the array and add it to returnedArray.

  4. The line returnedArray[i] = fn(arr[i], 1); is equivalent to returnedArray.push(fn(arr[i], 1));. Please excuse any confusion, as I am more familiar with Java.

I thought I had nailed it until I saw this wrong answer show up after running it. It turned out one test case failed.

image

After spending a while thinking and reviewing the challenge, I noticed they had specified that fn was already provided. All I had to do was adjust this line to returnedArray[i] = fn(arr[i], i). Quite straightforward, isn't it? No need to redefine the fn function. Let's give it another shot.

var map = function (arr, fn) {
  let returnedArray = [];
  for (let i = 0; i < arr.length; i++) {
    returnedArray.push(fn(arr[i], i));
  }
  return returnedArray;
};

And this, my friends, worked.