JavaScript Array filter() Method

In JavaScript, the filter method for arrays generates a new array that includes elements meeting a specified criterion. It is important to note that the filter method does not modify the original array in any way. Introduced in ECMAScript 5, the Array filter method has since established itself as an essential feature in JavaScript. This method is classified as a higher-order function.

Syntax

The syntax of the filter method is given below:

Example

const myArray = array.filter(callback(element, index, arr));

array: This refers to an array that we generate and subsequently filter its elements according to a particular criterion.

callback: It refers to a callback function that executes for every element within the array.

element: This refers to the specific item in the array that the callback function processes when utilizing the array filter method.

index: This is an optional parameter. It refers to the index of the element currently being processed within the array.

arr: This parameter is not mandatory. It refers to the complete array on which the .filter method has been invoked.

Examples of JavaScript Array filter

Example 1: Basic Array Filtering Using .filter Method

In this illustration, we will retrieve numbers that exceed a certain threshold from an array.

Example

Example

const myNumbers = [1, 2, 5, 6, 8, 10, 7, 15];

const myLargeNumbers = myNumbers.filter(function(number) {

        return number > 6;

});

console.log(myLargeNumbers);

Output:

Output

[ 8, 10, 7, 15 ]

Explanation:

In the preceding example, we established a variable identified as myNumbers utilizing const and initialized it with an array. We then filtered out all the values that exceed 6 and stored the outcome in the variable called myLargeNumber.

Example 2: User Filtering with .filter in JavaScript

In this tutorial, we will demonstrate the process of filtering an array of user objects according to particular criteria, a practice frequently encountered in practical applications.

Example

Example

const myUsers = [

  { name: 'Alice', age: 25, isActive: true },

  { name: 'Bob', age: 17, isActive: false },

  { name: 'Charlie', age: 30, isActive: true },

  { name: 'Diana', age: 16, isActive: true },

];



// Filter active users who are 18 or older



const eligibleUsers = myUsers.filter(function (user) {

  return user.isActive && user.age >= 18;

});

console.log(eligibleUsers);

Output:

Output

[

  { name: 'Alice', age: 25, isActive: true },

  { name: 'Charlie', age: 30, isActive: true }

]

Explanation:

In the preceding example, we established a variable called myUsers utilizing const. We initialized it with an array comprising objects. By employing the filter method, we extracted the data pertaining to active users aged 18 and above, which we then assigned to a variable named eligibleUsers.

Example 3: Searching for a product using an array.fliter method

In this example, we will utilize the filter method to locate the product.

Example

Example

const myProducts = [

  { name: "Laptop", category: "Electronics", price: 999 },

  { name: "Television", category: "Electronics", price: 79 },

  { name: "Wireless Mouse", category: "Electronics", price: 25 },

  { name: "Blender", category: "Kitchen", price: 45 }

];



// Function to search for products by name or category

function searchProducts(products, searchTerm) {

  const results = products.filter(function(product) {

    return product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||

           product.category.toLowerCase().includes(searchTerm.toLowerCase());

  });



  // If no results found

  if (results.length === 0) {

    return "Sorry, product not found.";

  }

  

  return results;

}



// Search for electronics

const electronicsResults = searchProducts(myProducts, "electronics");

console.log(electronicsResults);



// Search for products with "coffee" in the name

const coffeeResults = searchProducts(myProducts, "coffee");

console.log(coffeeResults);

Output:

Output

[

  { name: 'Laptop', category: 'Electronics', price: 999 },

  { name: 'Television', category: 'Electronics', price: 79 },

  { name: 'Wireless Mouse', category: 'Electronics', price: 25 }

]

Sorry, product not found.

Explanation:

In the code provided, we establish a variable referred to as myProducts using the const declaration, and we initialize it with an array consisting of objects. Each object corresponds to a product characterized by three attributes: name, category, and price. Within this array, we employed the .filter function, which retains solely those products that satisfy the specified criteria.

In this instance, product.name.toLowerCase.includes(searchTerm.toLowerCase) is employed to ascertain whether the name encompasses the search term. The logical OR (||) operator is utilized for this purpose. Similarly, product.category.toLowerCase.includes(searchTerm.toLowerCase) is applied to determine if the category contains the search term. If either of the elements, namely the name or the category, matches the search term, the item is returned; if not, a message stating "Sorry, product not found" is displayed. Initially, we searched for products that are present within the object, and subsequently, we conducted a search for those products that are absent.

Use cases of JavaScript filter method:

Here are various applications of the JavaScript filter method:

  • Filter data based on a condition : This is the most basic use case of the filter method in JavaScript. We can extract all numbers which is greater than a given value from an array of numbers or we can find all users in a list who are active.
  • Remove duplicates from an array : We can remove all the duplicate values from an array using the JavaScript array filter method.
  • Searching or finding items: When we need to retrieve a subset of elements that match a search criterion then the filter method is highly effective.
  • Creating a new array based on user input: In interactive applications, we frequently utilize a filter to update the shown data based on user selections or search queries.
  • Conclusion:

The filter method of JavaScript arrays is classified as one of the built-in methods. This method is quite powerful as it allows for the generation of a new array that includes only those elements from the original array that meet specific criteria. It serves various purposes, such as filtering data and eliminating duplicate entries from an array. In this article, we will explore the JavaScript Array filter method in depth, providing examples and addressing some commonly raised questions. We will examine various examples demonstrating the application of the filter method.

Frequently Asked Questions (FAQs):

  1. What does the JavaScript Array filter function do?

The filter function in JavaScript is considered one of the most robust built-in methods available. It generates a new array that includes all elements from the initial array that meet the criteria specified by a provided condition function.

  1. What is the mechanism behind the filter method?

In JavaScript, the filter method goes through every element in the original array. It runs a supplied callback function for each individual element. When the callback function returns true for a specific element, that element is incorporated into the new array; if it returns false, the element is excluded.

  1. What parameters does the callback function of filter accept?

The callback function can accept up to three arguments:

  • Element: The current element of the array is under process in the array.
  • Index: It is an optional parameter. The index of the current element being processed.
  • Array: It is an optional parameter. The array filter was called upon.
  1. What does the filter return if we pass an element that does not satisfy the condition?

When elements that do not meet the specified condition are provided, the filter method will yield an empty array ().

  1. What distinguishes the filter method from the map method and the forEach method in JavaScript?

filter method:

It identifies the specific elements that satisfy a particular condition and generates a new array that contains solely those elements.

map method :

It modifies every item in an array based on a specified function and produces a new array that maintains the same length as the altered values.

forEach:

It traverses through every item within an array to execute a specified operation, yet it does not generate a new array as a result. Its primary purpose is to facilitate side effects.

  1. Is it possible to apply filter on an array containing objects?

Indeed, it is possible to apply the filter method to an array of objects, and this practice is quite prevalent.

Example

Example

let users = [{name: 'Karan', age: 20}, {name: 'Ali', age: 25}];

let adults = users.filter (user => user.age >= 21);

console.log (adults);

Output:

Output

[ { name: 'Ali', age: 25 } ]
  1. Is it possible to apply filter to strings?

The filter method is not applicable to strings since it is exclusively designed for arrays. However, if you possess arrays containing strings, you can certainly apply the filter method to them.

Example

Example

let fruits = ['apple', 'banana', 'cherry'];

let search = fruits.filter (fruit => fruit.startsWith ('a'));

console.log (search);

Output:

Output

['apple']
  1. What makes filter a more favorable choice compared to utilizing a for loop?

This occurs as it is more concise, straightforward, and user-friendly. Additionally, it helps eliminate errors such as neglecting to append to a new array. This approach embodies a more functional programming style, which has become prevalent in contemporary JavaScript.

  1. Is filter exclusively for numbers?

No, the filter method is not limited to just numeric values. You can apply filter to arrays that consist of strings, numbers, objects, or any other data type. The crucial aspect is the condition specified in your callback function, and the method will operate based on that condition.

  1. Is it possible to terminate filter as soon as it identifies a match?

No, it is not possible to halt the process midway, indicating that the filter function evaluates every single element within the array. If you wish to terminate the operation prematurely, you might want to utilize find instead, as it retrieves the initial element that meets the specified criteria.

Input Required

This code uses input(). Please provide values below: