Exercise 13: Higher-Order Function: Filter Implementation

Problem Statement

Create a function `myFilter(arr, fn)` that is a custom implementation of array.filter().

Sample Output:

myFilter([1, 2, 3, 4], x => x % 2 === 0) => [2, 4]
myFilter([1, 2, 3], x => x > 1) => [2, 3]

Solution

const myFilter = (arr, fn) => {
  const result = [];
  for (let i = 0; i < arr.length; i++) if (fn(arr[i], i, arr)) result.push(arr[i]);
  return result;
};

Explanation

Overall Goal:

  • Array.filter() ka custom implementation.

Real world:

  • Understanding: how filter works.
  • Custom filtering: modified behavior.