Problem Description
Given an integer array arr
and a filtering function fn
, return a filtered array filteredArr
. The fn
function takes one or two arguments: arr[i]
- number from the arr
, and i
- index of arr[i]
. filteredArr
should only contain the elements from the arr
for which the expression fn(arr[i], i)
evaluates to a truthy value.
Key Insights
- The filtering function can take either one or two arguments (the element and its index).
- A "truthy" value is any value that evaluates to true when passed to the Boolean constructor.
- The solution must be implemented without using the built-in
Array.filter
method.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input array arr
, as we must examine each element once.
Space Complexity: O(n), for the space required to store the filtered result.
Solution
To solve the problem, we will iterate through each element of the input array arr
using a loop. For each element, we will call the filtering function fn
with the current element and its index. If the result of the function call is truthy, we will add that element to a new array. Finally, we will return the new array containing all the elements that passed the filter.
The approach involves:
- Initializing an empty array to store the filtered results.
- Looping through each element of the input array.
- Applying the filtering function to each element and its index.
- Checking if the result is truthy, and if so, adding the element to the results array.