for loop filtering 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 of products and filters out only the ones with the type ‘Fruites’. The filtered products are then logged to the console. Here’s a breakdown of the code:
<script>
{name: 'Cucumber', type: 'Vegitable'},
{name: 'Chilli', type: 'Vegitable'},
{name: 'Orange', type: 'Fruites'},
{name: 'Mango', type: 'Fruites'},
];
}
}
</script>
// Array of products
var products = [{name: 'Cucumber', type: 'Vegitable'},
{name: 'Chilli', type: 'Vegitable'},
{name: 'Orange', type: 'Fruites'},
{name: 'Mango', type: 'Fruites'},
];
// Empty array to store filtered products
var filteredProducts = [];
// Loop through each product in the 'products' array
for (var i = 0; i < products.length; i++) {
// Check if the current product's type is 'Fruites'
if (products[i].type === 'Fruites') {
// If true, push the product to the 'filteredProducts' array
filteredProducts.push(products[i]);}
}
// Log the filtered products to the console
console.log(filteredProducts);</script>
After executing this code, the console will display an array containing only the products with the type ‘Fruites’. In this case, the output will be:
[
{name: 'Orange', type: 'Fruites'},
{name: 'Mango', type: 'Fruites'},
]
{name: 'Orange', type: 'Fruites'},
{name: 'Mango', type: 'Fruites'},
]