Explorer
JavaScript

Write a function `myReduce(arr, callback, initialValue)` that works like Array.prototype.reduce.

Problem Statement

<p>Write a function <code>myReduce(arr, callback, initialValue)</code> that works like Array.prototype.reduce.</p>

Examples

Input: myReduce([1, 2, 3, 4], (acc, x) => acc + x, 0)

Output: 10

Explanation: Accumulates array items into a single final value.

Complexity

Time Complexity: O(N)

Space Complexity: O(N)

Hints

šŸ’” Hint 1: If initialValue is provided, start with it. Otherwise use arr[0] and start from index 1. šŸ’” Hint 2: Accumulate the result by calling callback(acc, currentValue, index, arr). šŸ’” Hint 3: Handle the case where no initialValue is given and the array is not empty.

Editorial & Approach

Problem Overview & Intuition

To solve Implement Array.reduce, we consider the execution characteristics of JavaScript engines. Write a function `myReduce(arr, callback, initialValue)` that works like Array.prototype.reduce. 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 (if initialvalue is provided, start with it. otherwise use arr[0] and start from index 1).
  3. Implement Logic: Handle state and transformations efficiently (accumulate the result by calling callback(acc, currentvalue, index, arr)).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function myReduce(arr, callback, initialValue) {
  let acc = initialValue !== undefined ? initialValue : arr[0];
  const startIndex = initialValue !== undefined ? 0 : 1;
  for (let i = startIndex; i < arr.length; i++) {
    acc = callback(acc, arr[i], i, arr);
  }
  return acc;
}

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.reduce

Medium

Write a function myReduce(arr, callback, initialValue) that works like Array.prototype.reduce.

Example Scenarios
1Example 1
Input: myReduce([1, 2, 3, 4], (acc, x) => acc + x, 0)
Output: 10
Explanation:

Accumulates array items into a single final value.

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