The Filter Method In JS: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the The Filter Method In JS.
The Filter Method In JS
The filter
method in JavaScript is used to create a new array that contains only elements from the original array that pass a certain test.
The filter
method takes a callback function as an argument, and this callback function is executed for each element in the original array.
If the callback function returns true
for a given element, that element is included in the new array. If it returns false
, that element is not included.
Here’s an example of using the filter
method:
const numbers = [1, 2, 3, 4, 5];
const even = number => number % 2 === 0;
const evenNumbers = numbers.filter(even);
console.log(evenNumbers);
Output
[2, 4]
In this example, we first define an array numbers
with 5 elements. Then, we define an even
function that takes a number and returns true
if it’s even and false
otherwise. Finally, we use the filter
method to apply the even
function to each element of the numbers
array, and return a new array evenNumbers
with only the even numbers.
The filter
method can also be used with arrays of objects, in a similar way:
const people = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Jim', age: 35 },
];
const adults = people.filter(person => person.age >= 18);
console.log(adults);
Output
[{ name: ‘John’, age: 30 }, { name: ‘Jane’, age: 25 }, { name: ‘Jim’, age: 35 }]
In this example, we define an array people
with 3 elements, each representing a person with a name
and an age
. Then, we use the filter
method to return a new array adults
with only the people who are 18 years old or older.
Conclusion
If you liked this post The Filter Method In JS, then please share this with your friends and make sure to bookmark this website for more awesome content.