Explorer
JavaScript

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

Problem Statement

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

Examples

Input: myFilter([1, 2, 3, 4], x => x % 2 === 0)

Output: [2, 4]

Explanation: Retains only elements satisfying the predicate.

Complexity

Time Complexity: O(N)

Space Complexity: O(N)

Hints

šŸ’” Hint 1: Create a new array for filtered results. šŸ’” Hint 2: Call the callback for each element; if it returns truthy, include the element. šŸ’” Hint 3: if (callback(arr[i], i, arr)) result.push(arr[i]);

Editorial & Approach

Problem Overview & Intuition

To solve Implement Array.filter, we consider the execution characteristics of JavaScript engines. Write a function `myFilter(arr, callback)` that works like Array.prototype.filter without using the built-in filter 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 for filtered results).
  3. Implement Logic: Handle state and transformations efficiently (call the callback for each element; if it returns truthy, include the element).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function myFilter(arr, callback) {
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    if (callback(arr[i], i, arr)) result.push(arr[i]);
  }
  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.filter

Medium

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

Example Scenarios
1Example 1
Input: myFilter([1, 2, 3, 4], x => x % 2 === 0)
Output: [2, 4]
Explanation:

Retains only elements satisfying the predicate.

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