How to filter an array - JavaScript

Mo Ibra

Mo Ibra

Dec 26, 2022

In this article we will learn how to filter an array.

It is very common to filter an array in JavaScript.


Problem

Now we have a problem, which is that we want to filter the array.

Imagine that we have an array with a set of numbers like this:

// Array
const array = [1, 2, 3, 4, 200, 300, 400]

And we want to delete the numbers above 100 to make it like this.

[1, 2, 3, 4]

How to solve this problem

Well, to solve this problem using filter method.


Filter an array using filter method

We can use filter to filter our array.

Example

// 1. Define an array
const array = [1, 2, 3, 4, 200, 300, 400];

// 3. Filter our array
const filter = array.filter(value => {

    // 4. If value more than 100
    if (value > 100) {

        // Don't add it to new array
        return false
    }

    // Otherwise add it to new array
    return true;
})

// Result:
console.log(filter);

Output

[ 1, 2, 3, 4 ]

How it works?

  • First, we defined our array const array
  • Second, we defined a new array const filter
  • Third, we filter our array using filter method
  • Then, we check if value is more than 100 or not
// 4. If value more than 100
if (value > 100) {

    // Don't add it to new array
    return false
}

// Otherwise add it to new array
return true;
  • If value more than 100, don't add it into new array
  • Otherwise add it.

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: