Sobes.tech
Intern — Senior

Custom implementation of the filter function

livecode

Task condition

Create your version of the filter function that takes two arguments: an array and a callback function.

 const filter = (arr, fn) => { };

Example 1:

  • Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
  • Output: [20,30]
  • Explanation: The function keeps only the elements greater than 10.

Example 2:

  • Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i == 0; }
  • Output: [1]
  • Explanation: The callback can receive the index of the element; here, it keeps the element at index 0.

Example 3:

  • Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
  • Output: [-2,0,1,2]
  • Explanation: Values that evaluate to false (e.g., 0) are discarded.