TobilobaCodes – LeetCode Explorer

2635. Apply Transform Over Each Element in Array

This problem requires creating a transformation function similar to Array.prototype.map, but without using .map(). For each element in the input array, the function should apply a given function fn using both the element and its index.

📄 Problem Statement

Given an integer array arr and a function fn, return a new array result such that:
result[i] = fn(arr[i], i)

Do not use Array.prototype.map().

💡 Example


Input:
arr = [1, 2, 3]
fn = function plusindex(n, i) { return n + i }

Output:
[1, 3, 5]
            

🧠 Explanation

We manually loop through the input array and apply the function fn to each element with its index. The results are stored in a new array that is returned.

✅ My Solution


/**
 * @param {number[]} arr
 * @param {(n: number, i: number) => number} fn
 * @return {number[]}
 */
var map = function(arr, fn) {
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        result.push(fn(arr[i], i));
    }
    return result;
};