Filter Elements from Array - Problem
Create your own array filtering function from scratch! You're given an integer array arr and a filtering function fn, and your task is to return a new filtered array containing only the elements that pass the test.
The filtering function fn can accept one or two parameters:
arr[i]- the current element from the arrayi- the index of the current element
Your filtered array should only contain elements where fn(arr[i], i) returns a truthy value. A truthy value is any value that makes Boolean(value) return true.
Challenge: You must implement this without using the built-in Array.filter() method!
Example: If arr = [0, 10, 20, 30] and fn = (n, i) => n > 10, then the result should be [20, 30] because only these elements are greater than 10.
Input & Output
example_1.js โ Basic Filtering
$
Input:
arr = [0, 10, 20, 30], fn = (n, i) => n > 10
โบ
Output:
[20, 30]
๐ก Note:
Elements 20 and 30 are greater than 10, so they pass the filter. Elements 0 and 10 do not satisfy the condition.
example_2.js โ Index-based Filtering
$
Input:
arr = [1, 2, 3], fn = (n, i) => i === 0
โบ
Output:
[1]
๐ก Note:
Only the element at index 0 (which is 1) satisfies the condition i === 0.
example_3.js โ Truthy Value Filtering
$
Input:
arr = [-2, -1, 0, 1, 2], fn = (n) => n + 1
โบ
Output:
[-2, 0, 1, 2]
๐ก Note:
The function returns n + 1. For -2: -1 (truthy), -1: 0 (falsy), 0: 1 (truthy), 1: 2 (truthy), 2: 3 (truthy).
Constraints
- 0 โค arr.length โค 1000
- -1000 โค arr[i] โค 1000
- fn returns a truthy or falsy value
- You cannot use the built-in Array.filter() method
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Create empty result array to store filtered elements
2
Iterate
Loop through each element in the input array with its index
3
Test
Apply the filtering function to current element and index
4
Filter
Add element to result array if function returns truthy value
5
Complete
Return the completed filtered array
Key Takeaway
๐ฏ Key Insight: Array filtering requires exactly one pass through the data - we test each element once and immediately decide whether to include it in our result, making this an inherently O(n) operation.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code