filter method in javascript

Explore our JavaScript category, where you’ll find loads of helpful articles and tutorials for everyone, whether you’re just starting out or a pro developer. Learn about different JavaScript functions that can be used in various projects according to their specific requirements.
This JavaScript code defines an array named products, containing objects representing different products with attributes such as name, type, quantity, and price. Following this, the filterProducts function filters the products array based on specific criteria. It selects products of type ‘Veg’, with a quantity greater than 0, and a price lower than 10.
<script>
var products = [
{ name: 'Cuc', type: 'Vege', quantity: 0, price: 1 },
{ name: 'Pota', type: 'Veg', quantity: 10, price: 9 },
{ name: 'Ban', type: 'Fru', quantity: 30, price: 9 },
{ name: 'Man', type: 'Fru', quantity: 3, price: 5 }
];
var filterProducts = products.filter(function (product) {
return product.type === 'Veg' && product.quantity > 0 && product.price < 10;
});
console.log(filterProducts);
</script>
In this JavaScript snippet, an array named products is initialized, containing various product objects with attributes such as name, type, quantity, and price. Subsequently, the filterProducts function is employed to sift through the array, selecting only those products that meet the specified conditions. Specifically, it identifies products categorized as ‘Veg’, with available quantities greater than zero, and priced below ten units. Finally, the filtered products are displayed via the console.