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 thearri- index ofarr[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,-1,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
Understanding the Visualization
1
Input Array
Original array [0,10,20,30] and filter function n > 10
2
Apply Filter
Test each element with the filter function
3
Filtered Output
Collect elements that pass: [20,30]
Key Takeaway
🎯 Key Insight: Build result array incrementally by testing each element with the filter function
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code