JavaScript is a popular and versatile programming language, and one of its most powerful features is its ability to work with arrays. One of the most useful functions for working with arrays is the filter. It allows you to filter elements of an array based on a given condition. Starting with ECMAScript 6, you can use arrow functions with the filter function to make your code even more concise.
The syntax of an arrow function is quite simple. It is written as:
(parameters) => {function body}
Here are five examples of how to use the function filterwith arrow functions:
1. Filter even numbers from an array:
const numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ];
const pairs = numbers.filter(num => num % 2 === 0 );
console.log(pairs); // [2, 4, 6, 8, 10]
2. Filter objects by a specific property:
const people = [
{name: "John" , age: 30 },
{name: "Maria" , age: 25 },
{name: "Joseph" , age: 35 },
{name: "Ana" , age: 20 }
];
const adults = people.filter(person => person.age >= 18 );
console.log(adults); // [{name: "John" , age: 30 }, {name: "Mary" , age: 25 }, {name: "Joseph" , age: 35 }]
3. Filter strings by size:
const words = [ "banana" , "apple" , "pear" , "pineapple" , "watermelon" ];
const short = words.filter(word => word.length <= 5 );
console . log (short); // [ "apple" , "pear" ]
4. Filter elements of an array of objects by a specific condition:
const cars = [
{ brand: "Fiat" , year: 2020 },
{ brand: "Ford" , year: 2015 },
{ brand: "Chevrolet" , year: 2010 },
{ brand: "Fiat" , year: 2016 }
];
const carsFiat = cars.filter(car => car.brand === "Fiat" );
console.log(carrosFiat); // [{brand: "Fiat", year: 2020}, {brand: "Fiat", year: 2016}]
5. Filter elements of an array of objects with multiple conditions:
const products = [
{ name: "Notebook" , price: 2500 , category: "electronics" },
{ name: "Smartphone" , price: 1500 , category: "electronics" },
{ name: "TV" , price: 3500 , category: "electronics" },
{ name: "Sofa" , price: 2000 , category: "furniture" },
{ name: "Bed" , price: 1500 , category: "furniture" }
];
const Cheapelectronics = products.filter(product => product.category === "electronics" && product.price <= 2000 );
console.log(eletronicosBaratos); // [{name: "Smartphone", price: 1500, category: "electronics"}]
As you can see, using arrow functions with the filter function makes your code more concise and easier to read. It’s a great way to filter elements from an array quickly and efficiently. Remember to always test your filter conditions to ensure you’re getting the results you expect.
Deixe um comentário