Filter Elements from Array - Problem

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
  • 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. A truthy value is a value where Boolean(value) returns true.

Please solve it without the built-in Array.filter method.

Input & Output

Example 1 — Filter Odd Numbers
$ Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
Output: [20,30]
💡 Note: Filter keeps elements > 10: greaterThan10(0)=false, greaterThan10(10)=false, greaterThan10(20)=true, greaterThan10(30)=true
Example 2 — Filter by Index
$ Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
Output: [1]
💡 Note: Filter keeps only first element: firstIndex(1,0)=true, firstIndex(2,1)=false, firstIndex(3,2)=false
Example 3 — No Elements Pass
$ Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1; }
Output: [-2,0,1,2]
💡 Note: Filter by truthy values: plusOne(-2)=-1 (truthy), plusOne(-1)=0 (falsy), plusOne(0)=1 (truthy), plusOne(1)=2 (truthy), plusOne(2)=3 (truthy)

Constraints

  • 0 ≤ arr.length ≤ 1000
  • -109 ≤ arr[i] ≤ 109
  • fn returns a boolean value

Visualization

Tap to expand
Filter Elements from Array INPUT arr = [0, 10, 20, 30] 0 i=0 10 i=1 20 i=2 30 i=3 Filter Function: function greaterThan10(n) { return n > 10; } Truthy: Boolean(value) = true Keep elements where fn returns a truthy value ALGORITHM STEPS 1 Initialize Result Create empty filteredArr = [] 2 Loop Through Array for i = 0 to arr.length - 1 3 Test Each Element Call fn(arr[i], i) 4 Collect if Truthy Push to result if true Evaluation: 0 > 10 --> false (skip) 10 > 10 --> false (skip) 20 > 10 --> true (keep) 30 > 10 --> true (keep) OK OK FINAL RESULT filteredArr = [20, 30] 20 30 Process Flow: [0, 10, 20, 30] n > 10 filter [20, 30] 2 elements passed filter Key Insight: Single Pass with Early Collection avoids using Array.filter() by manually iterating once through the array. For each element, we call fn(arr[i], i) and immediately push to result if truthy. Time: O(n), Space: O(k) where k = filtered count. TutorialsPoint - Filter Elements from Array | Single Pass with Early Collection
Asked in
Meta 25 Google 20 Microsoft 15
25.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen