JavaScript filter() Function

Subject: JavaScript

The filter() function in JavaScript is an array method used to create a new array with only those elements that pass a test provided by a callback function. It's ideal for selecting a subset of data from an array based on specific conditions.


What is filter() in JavaScript?

The filter() method goes through each element in an array and includes it in the new array only if the callback function returns true.

✅ The original array remains unchanged.


Syntax

Parameters:

  • currentValue: The current item in the array.
  • index (optional): Index of the current item.
  • array (optional): The entire array.

Example 1: Filter Numbers Greater Than a Value


Example 2: Filter Strings Based on Length


Example 3: Filtering Array of Objects


Example 4: Using filter() with Index


Example 5: Chaining filter() with map()


Common Use Cases

  • Filtering search results in a UI
  • Removing null, undefined, or falsy values
  • Filtering lists based on user input or permissions
  • Processing arrays of objects from APIs or JSON data

Key Takeaways

  • filter() is used to select elements from an array based on a condition.
  • It does not modify the original array.
  • Returns a new array with only the matching elements.
  • Can be combined with map(), reduce(), and other array methods for powerful transformations.
Next : Array Reduce