JS Built-ins
FunctionalProgrammingbeginner

Custom filter β€” higher-order function

πŸ“– Usage Example
function myFilter(arr, predicate) {
  const result = [];
  for (const item of arr) if (predicate(item)) result.push(item);
  return result;
}
myFilter([1, 2, 3, 4], x => x % 2 === 0); // [2, 4]

A custom filter passes only items for which the predicate returns true.

Filtering with Higher-Order Functions

Create a custom filter function that keeps only elements matching a predicate.

Challenge: Implement myFilter that takes an array and a predicate function, returning only elements where the predicate is true.

πŸ’‘ Hints (3)
  • β€’ Use reduce with conditional logic
  • β€’ Include x if predicate(x) is true
  • β€’ Otherwise keep accumulator unchanged