This content originally appeared on DEV Community and was authored by Mursal Furqan
So today, we shall be discussing about .filter() method in JavaScript.
The Filter Method
The filter() method in JavaScript takes each element in an array and it applies a conditional statement against it. If this conditional statement returns true, the element gets pushed to the output array. Otherwise, the element does not get pushed to the output array.
The filter() method creates a new array with elements that fall under a given criteria from an existing array.
Syntax
var first_array = arr.filter(
function callback(element, index, array) {
// Returns true or false
}[, thisArg])
The syntax for filter is similar to that of map, except, the callback function should return true to keep the elements, or false otherwise. In the callback, only the element is required.
Example
In the below given example, odd numbers are "Filtered" out, leaving only even numbers.
const all_numbers = [1, 2, 3, 4];
const even_numbers = all_numbers.filter(number => number % 2 === 0);
console.log(even_numbers);
// [2, 4]
In the next example, filter() is used to get all the students whose grades are greater than or equal to 90.
const students = [
{ name: 'Mursal', grade: 96 },
{ name: 'Furqan', grade: 48 },
{ name: 'Ahmed', grade: 99 },
{ name: 'Anees', grade: 56 },
{ name: 'Burhan', grade: 90 }
];
const studentGrades = students.filter(
students => students.grade >= 90);
return studentGrades;
//[ { name: 'Mursal', grade: 96 },
// { name: 'Ahmed', grade: 99 },
// { name: 'Burhan', grade: 90 } ]
In our next article, we are going to discuss something even cooler.
This content originally appeared on DEV Community and was authored by Mursal Furqan
Mursal Furqan | Sciencx (2021-07-04T04:06:43+00:00) JavaScript .filter() Method ?. Retrieved from https://www.scien.cx/2021/07/04/javascript-filter-method-%f0%9f%92%ad/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.