Problem Description
Given an integer array and a filtering function, return a filtered array that contains only the elements for which invoking the function with the element (and its index) returns a truthy value. Do this without using the built-in Array.filter method.
Key Insights
- Iterate over the provided array.
- For each element, call the filtering function with the element and its index.
- Append the element to the result array if the function returns a truthy value.
- Do not use built-in methods like Array.filter; implement the filtering manually.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n) in the worst case when every element passes the filtering condition.
Solution
The approach is straightforward: traverse the array using a loop, calling the provided filtering function for each element along with its index. If the function returns a truthy value (i.e., Boolean(value) evaluates to true), add that element to the resulting filtered array. This leverages a simple iterative loop and a temporary storage array, ensuring that we do not use any disallowed built-in filtering methods.