2634. Filter Elements from Array
This problem involves implementing a function similar to Array.prototype.filter but without using the built-in method.
The goal is to return a new array that only includes elements that return a truthy value when passed into the filtering function.
📄 Problem Statement
Given an integer array arr and a function fn, return a new array filteredArr such that:
filteredArr only contains the elements from arr for which fn(arr[i], i) returns a truthy value.
Do not use Array.prototype.filter().
💡 Example
Input:
arr = [0, 10, 20, 30]
fn = function greaterThan10(n) { return n > 10 }
Output:
[20, 30]
🧠 Explanation
We loop through the input array and pass each element and its index into the function fn. If the return value is truthy,
we include that element in a new array. The final result is returned after the loop finishes.
✅ My Solution
/**
* @param {number[]} arr
* @param {(n: number, i: number) => any} fn
* @return {number[]}
*/
var filter = function(arr, fn) {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i], i)) {
result.push(arr[i]);
}
}
return result;
};