DEV Community

Sarah Chima
Sarah Chima

Posted on • Updated on

JavaScript Filter Array Filter Arrays with the Javascript Filter() Method

Filtering unwanted elements to reduce the size of an array is fun right? JavaScript array filter method makes it even more fun.

In my last blog post, I wrote about the array map method in JavaScript. In case you missed it, this a link to the post. In an example there, we saw that we can use logical expressions in the callback function applied to elements in an array. Here is the code snippet below:

    const numbers = [4, 9, 36, 49];

    let oddSquareRoots = numbers.map((num) => {
       if(num % 2 != 0) {
           return Math.sqrt(num)     
       }
       return num;
    })

    console.log(oddSquareRoots);
Enter fullscreen mode Exit fullscreen mode

While this is possible, it is not ideal. A more efficient way is using the filter method. Now, let us answer the question: What is the filter method and how can we use it?

Understanding the Filter Method

According to MDN documentation:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Let us simplify this further by using an example.

If you have an array of random numbers (e.g ages of people) and you only need numbers that are above a certain number ( e.g 18). How will you do this using the normal for-loop?

    const ages = [11, 34, 8, 9, 23, 51, 17, 40, 14];

    let olderThan18 = [];

    for (let i = 0; i < ages.length; i++) {
        if(ages[i] > 18){
            olderThan18.push(ages[i])
        }
    }

    console.log(olderThan18); // [34, 23, 51, 40]

Enter fullscreen mode Exit fullscreen mode

This is much simpler using the filter method as shown below:

    const ages = [11, 34, 8, 9, 23, 51, 17, 40, 14];

    let olderThan18 = ages.filter((age) => age > 18);

    console.log(olderThan18); //[34, 23, 51, 40]

Enter fullscreen mode Exit fullscreen mode

P.S: We use arrow functions in the example. If you do not understand its syntax, please refer to this post on it.

We get the same result without the for-loop and it is much easier to use.

If we decide to declare the callback function before using it with the filter method, we can do this:

    const ages = [11, 34, 8, 9, 23, 51, 17, 40, 14];
    const isOlderThan18 = (age) => age > 18;

    let olderThan18 = ages.filter(isOlderThan18);

    console.log(olderThan18); // [34, 23, 51, 40]

Enter fullscreen mode Exit fullscreen mode

Let us look at the syntax of the filter method.

The Filter() method's syntax

The basic syntax for the filter method is this:

    let newArray = array.filter(callback);
Enter fullscreen mode Exit fullscreen mode

where

  • newArray - the new array that is returned
  • array - the array on which the filter method is called
  • callback - the callback function that is applied to each element of the array

The callback function can take three arguments

  • element - the current element being processed
  • index - the index of the current element being processed
  • array - the original array the filter was called on

Having these arguments in mind, we can also write the syntax as:

   let newArray = array.filter(callback(element, index, array));

   or

   let newArray = array.filter((element, index, array) => {
        //filter 'em elements
    })
Enter fullscreen mode Exit fullscreen mode
Here are some things to note about the filter method.
  1. It returns a new array.

  2. It does not mutate the original array on which it was called i.e the original array stays the same.

  3. The range of element processed by the filter method is set before the first invocation. If new elements are added to the array after the map begins, it will not be processed by the callback.

When to use the Filter Method

When you want only items that meet a required condition in an array.

Examples of using the filter method

Here are two examples of what we can do with the filter method.

Example 1: Filtering an array of objects

If you have an array of countries and you want only countries that are in a particular continent. This is an example of how you can do that using array filter method.

    const countries = [
        { name: 'Nigeria', continent: 'Africa'},
        { name: 'Nepal', continent: 'Asia'},
        { name: 'Angola', continent: 'Africa'},
        { name: 'Greece', continent: 'Europe'},
        { name: 'Kenya', continent: 'Africa'},
        { name: 'Greece', continent: 'Europe'}
    ]

    let asianCountries = countries.filter(country => {
        return country.continent === 'Asia';
    })

    console.log(asianCountries); // [{name: "Nepal", continent: "Asia"}]
Enter fullscreen mode Exit fullscreen mode

Example 2: Search for specific letters in an array

Given an array of words and you want to find out which of the words contains specific letters. For example, you want female names that contain specific alphabets together, here is how you can do it.

    const names = ['Victoria', 'Pearl', 'Olivia', 'Annabel', 'Sandra', 'Sarah'];
    const filterItems = (letters) => {
        return names.filter(name => name.indexOf(letters) > -1);
    } 

    console.log(filterItems('ia')); // ["Victoria", "Olivia"]
Enter fullscreen mode Exit fullscreen mode

Conclusion

So in this post, we have seen how easy the JavaScript Filter method makes filtering elements in an array.

Remember the example mentioned at the beginning of this post? Can you try to use the filter method to achieve the same thing?

Got any question or addition? Please leave a comment.

Thank you for reading :)

Shameless Plug🙈

If you want to know more about me, here's a link to my website.

Latest comments (9)

Collapse
 
frontendengineer profile image
Let's Code

Hi Sarah, great post! Happen to record a video about js filter similar topic like you did here. Thanks for educating the community.

youtube.com/watch?v=hvUs_mQc_wo&li...

Collapse
 
budisalah profile image
Budi Salah 🐋 • Edited

Hello guys.
I need some help, please 😥

At the end of this post, @sarah_chima said

Remember the example mentioned at the beginning of this post? Can you try to use the filter method to achieve the same thing?

I tried to do it but I can't. I want the final output to be like this using filter method:

[4, 3, 36, 7]

Thanks, guys.

Collapse
 
vier31 profile image
Jan Schröder

You would need to put the if statement in the callback of the filter()

const oddSqrRoots = numbers.filter(num => num % 2 != 0)

Collapse
 
stephencweiss profile image
Stephen Charles Weiss

Great post Sarah! Thanks for writing it and beautiful website too by the way :).

Off topic: When you write on Dev.to... which style are you using for your code snippets? I've been using gist (since it's what I do on my site), but yours is so much prettier!

Collapse
 
vier31 profile image
Jan Schröder • Edited

From what it looks like on my end, the code snippets are inside triple backticks in the markdown, which creates this kind of code snippet in the article. Plus the definition of the language after the initial three backticks.

Collapse
 
raiivis profile image
Raivis Vasiļevskis

Nicer synthax doesn't always mean better results. This way is slower than traditional for loop. Probably it does not matter for small arrays, but try to test it with large arrays. You will see quite a big difference in the speed

Collapse
 
joelnet profile image
JavaScript Joel

This statement is misleading. In reality there will be zero impact to performance within an application. Unless you are designing a game engine, this metric is worthless.

Collapse
 
teexee19 profile image
Tochukwu Franklin Ene

Awesome!! thanks Sarah.

Collapse
 
joelnet profile image
JavaScript Joel

I have fallen in love with this syntax over a for loop:

const isOlderThan18 = (age) => age > 18;

The reason being, with a for loop, the focus is on operating on the collection as a whole.

By making this minor change, we have simplified our work to just operating on a single item and not a whole collection of items, which is more complex.

Once we have solved how to handle the single item, it becomes easy to then apply that solution also to the collection.

const map = require('ramda/src/map')

const isOlderThan18 = (age) => age > 18;
const mapOlderThan18 = map(isOlderThan18)

const olderThan18 = mapOlderThan18(ages)

Cheers!