SoFunction
Updated on 2025-04-12

How to use filter method to filter array elements in JS

Array traversal related questions: How to usefilter()Method to filter array elements?

In JavaScript,filter()Method is a very common and practical array traversal method that is used to filter elements in an array and return a new array containing all elements tested by the callback function.

This article will explain in detail how to use itfilter()The method filters array elements and demonstrates them in combination with actual project code examples to help everyone better understand how to use them.

1. Introduction

In JavaScript,filter()Methods are used to filter out elements that meet certain criteria from an array and return a new array. andmap()Different methods,filter()The returned array contains only elements that meet the conditions, and ignores elements that do not meet the conditions.

filter()is immutable, i.e. it does not change the original array, but returns a new array.

2. Basic use of filter() method

filter()Method Overview

filter()Methods are used to filter out elements in an array that meet the criteria. It accepts a callback function as a parameter, which performs some conditional test on each array element, and returnstrueorfalse. If returntrue, the element will be kept in the new array; if returnedfalse, then this element will be excluded.

grammar

let newArray = (function(currentValue, index, array) {
  // Return true or false to determine whether the element is retained});
  • currentValue: The value of the current element.
  • index: The index of the current element (optional).
  • array: The original array itself (optional).

Example: Basicfilter()use

let arr = [1, 2, 3, 4, 5];
let evenNumbers = (function(value) {
  return value % 2 === 0;  // Only even numbers are retained});
(evenNumbers);  // Output:[2, 4]

In the above code,filter()Method traversing the arrayarrEach element in it and according to the conditionsvalue % 2 === 0Filter out all even numbers and return a new arrayevenNumbers

3. Comparison of filter() with other traversal methods and map()

map()andfilter()All are array traversal methods, but their purpose is different:

  • map()Used to iterate over the array and return a new array. Each element of the array is the result of the original array element being processed by the callback function.
  • filter()Used to filter elements in an array and return a new array containing elements that match the criteria.

map()Example:

let arr = [1, 2, 3, 4, 5];
let doubled = (function(value) {
  return value * 2;  // Double each element});
(doubled);  // Output:[2, 4, 6, 8, 10]

filter()Example:

let arr = [1, 2, 3, 4, 5];
let evenNumbers = (function(value) {
  return value % 2 === 0;  // Only even numbers are retained});
(evenNumbers);  // Output:[2, 4]

andforEach()Comparison

forEach()andfilter()All can be used to traverse arrays, but there are several key differences:

  • forEach()A new array is not returned, it just executes a function on each element in the array.
  • filter()A new array will be returned, and the new array will contain only elements that meet the criteria.

forEach()Example:

let arr = [1, 2, 3, 4, 5];
(function(value) {
  (value * 2);  // Output: 2, 4, 6, 8, 10 (no new array returned)});

filter()Example:

let arr = [1, 2, 3, 4, 5];
let evenNumbers = (function(value) {
  return value % 2 === 0;  // Only even numbers are retained});
(evenNumbers);  // Output:[2, 4]

andreduce()Comparison

reduce()It's a differentfilter()method, it is used to aggregate all elements in an array into a single value (such as sum, maximum value, etc.), andfilter()A new array for returning elements that meet the criteria.

reduce()Example:

let arr = [1, 2, 3, 4, 5];
let sum = (function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
(sum);  // Output:15(The sum of array elements)

4. Example of filter() usage in actual project

Example 1: Filter products that meet the criteria

Suppose you have a product list with the name and price of each product, and you want to filter out products that are priced at more than 100.

let products = [
  { name: 'Laptop', price: 1200 },
  { name: 'Phone', price: 800 },
  { name: 'Tablet', price: 150 },
  { name: 'Charger', price: 20 }
];
let expensiveProducts = (function(product) {
  return  > 100;  // Filter out products with prices greater than 100});
(expensiveProducts);

Output:

[
  { name: 'Laptop', price: 1200 },
  { name: 'Phone', price: 800 },
  { name: 'Tablet', price: 150 }
]

Example 2: Filter user data

Suppose you have a user list containing information such as name, age, etc., and you want to filter out users older than 18.

let users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 17 },
  { name: 'Charlie', age: 30 },
  { name: 'David', age: 15 }
];
let adults = (function(user) {
  return  > 18;  // Filter out users older than 18});
(adults);

Output:

[
  { name: 'Alice', age: 25 },
  { name: 'Charlie', age: 30 }
]

Example 3: Filter data in asynchronous operations

When handling asynchronous operations, you can usefilter()CombinedPromiseTo filter the results of asynchronous operations. For example, suppose you need to filter out API data that meets certain criteria.

let ids = [1, 2, 3, 4, 5];
let promises = (function(id) {
  return fetch(`/posts/${id}`)
    .then(response => ());
});
(promises).then(function(posts) {
  let filteredPosts = (function(post) {
    return  === 1;  // Only posts with userId of 1 are retained  });
  (filteredPosts);
});

5. Summary and best practices

filter()It is a very powerful array traversal method that can filter elements in an array according to specified conditions and return a new array. It is often used to extract subsets that meet certain criteria from large data sets.

usefilter()When you are experiencing the following best practices:

  • Make sure that the return of the callback function istrueorfalse, to determine whether the element is retained.
  • usefilter()It can avoid manually handling loop conditions and keep the code concise.
  • When processing asynchronous data, you can usePromiseUse it in conjunction with the flexibility to filter data.

masterfilter()Methods will help you process and filter data efficiently in real projects.

This is the end of this article about how to use the filter() method to filter array elements in JS. For more related js filter() method to filter array elements, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!