How to use JavaScript filter method in an array.

When are javascript filters used? And what is the syntax? All these questions will be explored in this article.

In this article, you will learn how to use the JavaScript Array filter() method to filter elements in an array.

I. What can .filter() method do?

As the name implies, this method is used to filter out the elements in the array that satisfy a given condition. It will then return a new array containing those elements.

Note: As Array.filter() returns a new array, filter() does not change the value of the original array.

The syntax of the forEach() method is:

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

The callback function takes three arguments:

  • currentElement: the current element in the array
  • index: the index of the currentElement (optional)
  • array: The array object (optional)

The thisArg argument of the filter() method is optional. If you pass the this value, you canreference it by using this keyword inside the callback function.

II. For loop vs. filter()

For example, we need to find students that are older than 18:

// for loop

const ages = [15, 6, 9, 20, 25, 14, 30];

let olderThan18 = [];

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

console.log(olderThan18); // [20, 25, 30]

JavaScript filter() method allows us to do this task in a shorter and cleaner way.

// filter method

const ages = [15, 6, 9, 20, 25, 14, 30];

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

console.log(olderThan18); // [20, 25, 30]