What is Javascript Filter Method With Examples

Javascript Array Filter Method Explained With Examples


The JavaScript filter() method is used to filter an array based on specified conditions. Conditions is provided with the help of a callback function that is passed to the filter method as a parameter. The callback function is called for each element in the array. When the filter method’s running is done, it returns a new array with all the elements that pass the filter.

In this tutorial, we will explain the syntax of the JavaScript filter method, how it works, and how to use it with different data types, along with practical examples. Let’s get started.

Syntax

The filter method in JavaScript has a straightforward syntax. It accepts a callback function as a parameter that determines whether an item should be included in the resulting array. For the callback function, you can prefer using a regular js function or an arrow function.

The syntax of a filter method is as shown below:

const filteredArray = array.filter(function(current, index, itself){return <condition>})
const filteredArray = array.filter((current,index,itself) => <condition>) // Arrow function

Where,

  • array: The original array on which the filter method is invoked.
  • function: A callback function called for each element in the array. Three arguments can be passed:
    • current: The current element being processed.
    • index (optional): The index of the current element being processed.
    • itself (optional): The array itself
  • filteredArray: The array including elements that meet criterias

How Does Javascript Filter Method Works

How Javascript array filter method works

The filter method iterates over each element of the array and calls the provided callback function for each element. The callback function returns a boolean value indicating whether the item should be included in the resulting array. If the callback function returns true, the item is added to the new resulting array. If the callback function returns false, the item is skipped.

The filter method does not modify the original array; instead, it creates and returns a new array containing the filtered elements.

Let’s say you have an array including positive or negative numbers and you want to obtain only positives. In this case, the filter method can be used as in the following code snippet:

const numbers = [-2, -1, 0, 1, 2, 3, 4, 5];
const positiveNumbers = numbers.filter(function(number) {
  return number > 0;
});

console.log(positiveNumbers); // Output: [1, 2, 3, 4, 5]

For example, in this code snippet, since the number -1 does not meet the condition number > 0, the callback function will return false for this value and it will not be included in the filtered list. On the other hand, since the number 2 meets the condition, the callback function will return true for this value and it will be included in the final filtered list.

Use Cases and Examples

Javascript filter method is used with arrays containing elements of different types, such as strings, numbers, booleans, objects and even dates. Let’s different examples of the filter method.

Filter Method With Two or Multiple Conditions

If you want to filter an array based on multiple conditions, you can use the && (and) operator so that if an item meets these multiple criteria, it will be added to the new filtered array.

For example, if we take the example above, to get positive numbers and also numbers less than 3, you can modify the example above as in the following snippet:

const numbers = [-2, -1, 0, 1, 2, 3, 4, 5];
const filtered = numbers.filter(function(number) {
  return number > 0 && number < 3;
});

console.log(filtered); // Output: [1, 2]

Remove Duplicates From An Array

In some cases, you can combine other array methods with the filter method. For example, to remove duplicate elements in an array, you can utilize the indexOf method.

const numbers = [1, 2, 2, 3, 4, 4, 5, 5];

const uniqueNumbers = numbers.filter(function(number, index, array) {
  return array.indexOf(number) === index;
});

console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]

The indexOf method returns the first index in the array of the element given as a parameter. If there are any duplicate items in the array, the value returned by the indexOf method will not match the index of the item in the filter method for duplicate items except the first one. As a result, it will only return the elements once.

Filter Method With Array Of Objects

Objects consist of key and value pairs. You can filter objects that meet a criterion based on the object’s values. Let’s say we have array of objects containing people and objects has two keys, name and age. You want to get people over 18 years old from this array.

Here’s how to achieve this:

const people = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 17 },
  { name: 'Adam', age: 19 },
  { name: 'Emily', age: 22 },
  { name: 'Michael', age: 16 }
];

// Filter people over 18 years old
const adults = people.filter(function(person) {
  return person.age > 18;
});

console.log(adults);

// Output: [
//   { name: 'John', age: 25 },
//   { name: 'Adam', age: 19 },
//   { name: 'Emily', age: 22 }
// ]

Filter By Date

You can use also the JavaScript filter method to filter an array of dates based on certain criteria.

Here is an example:

const dates = [
  new Date('2022-01-15'),
  new Date('2022-03-05'),
  new Date('2022-06-10'),
  new Date('2022-09-22'),
  new Date('2022-11-30'),
  new Date('2023-02-14')
];

// Filter dates after a specific date
const filteredDates = dates.filter(function(date) {
  const referenceDate = new Date('2022-07-01');
  return date > referenceDate;
});

console.log(filteredDates);
// Output: [
//   '2022-09-22T00:00:00.000Z',
//   '2022-11-30T00:00:00.000Z',
//   '2023-02-14T00:00:00.000Z'
// ]

In this code snippet, we filter an array of dates (dates) and keep only those dates that come after a specific reference date (2022-07-01).

Filter Method With Arrow Function

We have used traditional JavaScript function syntax as a callback parameter in our filter methods. However, you can also use an arrow function introduced with ES6, reducing code complexity and increase readability.

const numbers = [-2, -1, 0, 1, 2, 3, 4, 5];
const filtered = numbers.filter((number) => number > 0 && number < 3);

console.log(filtered); // Output: [1, 2]

Filter vs Find

If you have exprience on other javascript array methods, you may realize the similarities the filter method with the find method. However there is a big difference between them. The filter method is used to get multiple elements that meet a condition, while find is used to find the first element that satisfies a condition.

Filter vs Find Array Methods in Javascript

Here is an example:

const numbers = [1, 2, 3, 4, 5];

const filtered = numbers.filter(function(number) {
  return number > 3;
});

console.log(filtered); // Output: [4, 5]

const found = numbers.find(function(number) {
  return number > 3;
});

console.log(found); // Output: 4

Conclusion

The javascript filter is a built-in array method that is widely used to retrieve elements in an array based on some condition. It has a wide range of uses because we can work with multiple types and can be combined with other array methods.

This article explained the javascript array filter method’s syntax, how it works, its different use cases, providing practical examples for each.

If you want to learn more about JavaScript, then you can check the following articles:

Thank you for reading.

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top