Write a function `myFilter(arr, callback)` that works like Array.prototype.filter without using the built-in filter method.
Problem Statement
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
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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (create a new array for filtered results).
- Implement Logic: Handle state and transformations efficiently (call the callback for each element; if it returns truthy, include the element).
- 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
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.