Filter

//ES5 Solution
var products = [
    {name: 'cucumber', type: 'vegetable'},
    {name: 'banana', type: 'fruit'},
    {name: 'celery', type: 'vegetable'},
    {name: 'orange', type: 'fruit'},
]

var filteredProducts = []; 
for (var i = 0; i<products.length; i++){
    if(product[i].type === 'fruits') {
        filteredProducts.push(products[i]); 
    }
}

//ES6 Solution
//Looks similar to map, it takes an element and goes into the iterator function.
//The iterator function has to return a true/false, if its true, it gets added in the result array 
products.filter(function(product){
    return product.type === 'fruits'; 
});


//More complex filter:
var products = [
    {name: 'cucumber', type: 'vegetable', quantity: 0, price: 1},
    {name: 'banana', type: 'fruit', quantity: 2, price: 5}},
    {name: 'celery', type: 'vegetable', quantity: 12, price: 15}},
    {name: 'orange', type: 'fruit', quantity: 5, price: 5}},
]

//Type is 'vegetable', quantity is greater than 0, prices s less than 10
products.filter(function(product){
    return product.type === 'fruits' 
    && product.quantity > 0
    && product.price < 10  ; 
});

results matching ""

    No results matching ""