Explorer
JavaScript

Write a function `myMap(arr, callback)` that works like Array.prototype.map without using the built-in map method.

Problem Statement

<p>Write a function <code>myMap(arr, callback)</code> that works like Array.prototype.map without using the built-in map method.</p>

Examples

Input: myMap([1, 2, 3], x => x * 2)

Output: [2, 4, 6]

Explanation: Transforms every item through the callback.

Complexity

Time Complexity: O(N)

Space Complexity: O(N)

Hints

šŸ’” Hint 1: Create a new array to store results. šŸ’” Hint 2: Loop through the array and call the callback with (element, index, array). šŸ’” Hint 3: Push the callback result into the new array for each element.

Editorial & Approach

Problem Overview & Intuition

To solve Implement Array.map, we consider the execution characteristics of JavaScript engines. Write a function `myMap(arr, callback)` that works like Array.prototype.map without using the built-in map method. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (create a new array to store results).
  3. Implement Logic: Handle state and transformations efficiently (loop through the array and call the callback with (element, index, array)).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function myMap(arr, callback) {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    result.push(callback(arr[i], i, arr));
  }
  return result;
}

Complexity Analysis

Time Complexity O(N) single linear scan through array
Space Complexity O(N) new output array (O(1) for reduce)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Implement Array.map

Medium

Write a function myMap(arr, callback) that works like Array.prototype.map without using the built-in map method.

Example Scenarios
1Example 1
Input: myMap([1, 2, 3], x => x * 2)
Output: [2, 4, 6]
Explanation:

Transforms every item through the callback.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[[2,4,6],["a0","b1"]]