The Filter Elements from Array interview question is a functional programming task, usually in JavaScript. You are asked to implement a function that takes an array and a "filtering function" (callback). Your function should return a new array containing only the elements for which the filtering function returns a truthy value. This is a custom implementation of the built-in Array.prototype.filter() method.
Companies like Amazon and Google ask this to test your understanding of Higher-Order Functions and callbacks. It evaluates if you can write clean, generic code that works with logic provided by the caller. It also checks your familiarity with array iteration and memory management (creating a new array instead of modifying the original).
This problem follows a simple Linear Scan with Callback pattern.
for loop.i:
fn(arr[i], i).arr[i] into the result array.Array: [10, 20, 30], Filtering function: (x) => x > 15.
10 > 15 is false. Skip.20 > 15 is true. Add 20.30 > 15 is true. Add 30.
Result: [20, 30].1, "hello", and {} are "truthy" and should be treated as true.i as a second argument.Be ready to explain why you use a for loop instead of forEach or map. Usually, a standard for loop is preferred for custom implementations to avoid unnecessary function overhead or to allow for early exits (though filter doesn't exit early).
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Biggest Single Number | Easy | Solve | |
| DI String Match | Easy | Solve | |
| Find First Palindromic String in the Array | Easy | Solve | |
| Kth Distinct String in an Array | Easy | Solve | |
| Largest Triangle Area | Easy | Solve |