Contact Us

How to use JavaScript’s method filter to handle arrays: Full Guide

 - 
July 25, 2022

One of the most popular cases that developers face a lot is when you have an array and you want to exclude some elements from it dynamically. For example you have an array full of names, and you want to remove the name Jack and the name Jimmy from the array. In this case the best solution is to use the filter() method.

What is the filter() method ?

The filter method is a JavaScript function that filters elements from an array based on a set of conditions. It was introduced in ECMAScript 5. This method is very useful if you want to remove some elements from an array based on some given conditions. It return a new array that contains only the elements you need.

What this method does is that it evaluate each element of the array based on the given condition and if the element gives true it stores the element in a new array. However, if an element give back a false then it will be excluded.

The syntax of the method

const returnValue = array.filter((value, index, array) => {...}, thisArg);

The filter method takes one argument which a callback array which will take three arguments.

  • The first argument is the value of the current element.
  • The second element is the current index.
  • The third and the last element is the array we are going through.

The first argument which is the value is required, but the index and the array arguments are optional.

The method will create a new array and store every true evaluated element inside of it, and at the end it returns the new array.

Filter method example

In this section we are going to give a real world example of using the filter method in JavaScript. First let’s suppose we have an array that this full of objects that holds data about some books like the following.

const books = [
      { 'id': 1, 'title': 'Ulysses', 'publicationYear': 2019 },
      { 'id': 2, 'title': 'the lean startup', 'publicationYear': 2020 },
      { 'id': 3, 'title': 'rich dad poor dad', 'publicationYear': 2021 },
      { 'id': 4, 'title': 'the 7 habits of highly effective people', 'publicationYear': 2021 },
    ]

The goal of this example is to get only the books that was published between 2020 and 2022, which means our condition will based on the publicationDate.

The following code will return a new array with the books that was published between 2020 and 2022.

const recentBooks = books.filter(book => book.publicationYear >= 2020);

As you can see in the following image, this is the result of the filter method that we just executed. It returned a new array with only the books that was published between 2020 and 2022.

[
  { 'id': 2, 'title': 'the lean startup', 'publicationYear': 2020 },
  { 'id': 3, 'title': 'rich dad poor dad', 'publicationYear': 2021 },
  { 'id': 4, 'title': 'the 7 habits of highly effective people', 'publicationYear': 2021 }
]

Comparing the filter method with the classic way of filtering

We just saw how we can filter an array easily using the filter method. Now, let’s take a look into how we can filter an array without using any built-in function in JavaScript, and to achieve that we are going to use the basic for loop in JS.

let recentBooks = [];
for (let i = 0; i < books.length; i++) {
    if (books[i].publicationYear > 2020) {
        recentBooks.push(books[i]);
    }
 }

As you can see we looped through the array, and we pushed the books that was published between 2020 and 2022 in a new array.

The difference between the filter method and the basic for loop is first the number of lines that we had to write using the for loop is much bigger than the number of lines that we wrote using the filter method. Second is the performance. Writing a snippet of code using the filter method will always be much performant than using a for loop.

Other methods like filter

JavaScript is a very rich language because it provides a lot of methods to handle arrays like the filter method. Here are some other array methods in JavaScript that may help you.

  • map()  :  This method make some changes on a given array and return a new array with the result
  • sort()  :   This method sort the elements of an array.
  • find()  :   This method return the first element in an array that satisfies the condition.
  • findIndex()  :  This method return the index of the first element in an array that satisfies the condition.
  • includes()   :  This method check if an array contains a given element.

Conclusion

In this article we have learned how to use the filter method in JavaScript in order to remove some elements from the array based on a set of conditions.

Web Design Services

Looking for a web design agency to bring your business online and build the website you need to get more high quality clients ?
GrowYourBusiness.tech agency is ready to help you build your beautiful looking website.

Latest Blogs

We are a team of creative thinkers and problem solvers dedicated to expanding the limits of what is possible by helping brands achieve their goals.

Social Media

Copyright © 2021 Grow Your Business. All rights reserved.
crossmenu