Free UI Resources - UI Dev Made Easy
Javascript

Javascript Array Methods – .filter()

.filter()

The .filter() method is another useful function provided by JavaScript arrays. It allows you to create a new array containing only the elements that meet a certain condition defined by a filtering function. This method is especially handy when you want to extract specific items from an array based on some criteria.

Here’s the basic syntax of the .filter() method:

const newArray = array.filter(function(currentValue, index, array) {
  // Return true or false to determine if the element should be included in the new array
});
  • currentValue: The current element being processed in the array.
  • index (optional): The index of the current element.
  • array (optional): The array that .filter() is being applied to.

The .filter() method returns a new array containing only the elements for which the filtering function returns true.

Here’s an example to illustrate how .filter() works:

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

const evenNumbers = numbers.filter(function(number) {
  return number % 2 === 0;
});

console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]

In this example, the .filter() method uses the filtering function to keep only the even numbers from the numbers array, resulting in a new array called evenNumbers.

You can also use arrow functions for more concise syntax:

const oddNumbers = numbers.filter(number => number % 2 !== 0);

Keep in mind the following points when using .filter():

  1. New Array: The .filter() method creates and returns a new array, leaving the original array unchanged.
  2. Condition: The filtering function should return a boolean value (true or false). Elements that evaluate to true will be included in the new array.
  3. Use Cases: .filter() is great for extracting elements that meet specific criteria, such as selecting all strings that start with a certain letter or filtering out items that don’t meet a certain threshold.
  4. Order: The order of elements in the resulting array will be the same as in the original array.
  5. Filtering to Objects: You can also use .filter() to extract objects from an array of objects based on specific properties.

In summary, the .filter() method is a powerful tool for creating a new array that contains only the elements that satisfy a given condition defined by a filtering function. It’s commonly used when you need to extract specific elements from an array based on certain criteria.

back to top