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.
As the name implies, this method filters 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:
The thisArg
argument of the filter() method is optional. If you pass the this
value, you can reference it by using the this
keyword inside the callback function.
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]
filter() method allows us to do this task more shortly and cleanly.
// filter method
const ages = [15, 6, 9, 20, 25, 14, 30];
let olderThan18 = ages.filter((age) => age > 18);
console.log(olderThan18); // [20, 25, 30]