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 array
  • i - 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
0102030Input ArrayFiltering Functionfn(element, index)Test each element2030Filtered ResultโŒ fn(0,0) โ†’ falseโŒ fn(10,1) โ†’ falseโœ“ fn(20,2) โ†’ trueโœ“ fn(30,3) โ†’ trueAdd to result
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.
Asked in
Amazon 45 Google 38 Meta 32 Microsoft 28
42.3K Views
High Frequency
~15 min Avg. Time
1.9K 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