JavaScript arrays have a filter() method that let you create a new array containing just the elements you need. Here are 5 common examples that demonstrate how to use filter().

  1. Filtering an Array of Primitives
  2. Filtering an Array of Objects
  3. “Removing” a Value
  4. Using Lodash’s matches()
  5. Interacting with Other Functional Helpers

1) Filtering an Array of Primitives

The filter() function takes a callback, and returns a new array containing just the elements that callback returned truthy for. This means you can use filter() to filter arrays of primitives, like finding all elements in an array of strings that start with “A”, or finding all even numbers in an array:

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

nums.filter(function isEven(num) {
  return num % 2 === 0;
}); // [2, 4, 6, 8, 10]

#javascript #developer

Understand the JavaScript Array Filter Function in 5 Examples
2.10 GEEK