ES6, Javascript

Breaking down ES6: filter() Method

Just as how it’s name sounds this method will filter out elements from an array. Let’s see it working.
Let’s say that we have an array of produce and we want to filter out or sort some products.
var products = [
    {name: ‘cucumber’, type: ‘vegetable’},
    {name: ‘banana’, type: ‘fruit’},
    {name: ‘celery’, type: ‘vegetable’},
    {name: ‘orange’, type: ‘fruit’}
]
We have items from a grocery store. We have an array of objects and each item has it’s own item.
Maybe the user wants to see only fruit.
The way we used to do this in the past with a for loop is by doing:
Past
var filereredProducts = [];
for (var i = 0; i < products.length; i++) {
    if (products[i].type === ‘vegetable’) {
        filteredProducts.push(products[i]);
    }
}
filteredProducts;
This will return only the items that are of type fruit.
We don’t want to mutate the existing arrays because we don’t want to get rid of the fruits because we might want to use it later.
Present
 
With ES6 and the filter method we cad do this with cleaner looking code .
var filteredProducts = products.filter(function(product) {
    return (product.type === ‘vegetable’);
}) ;
filteredProducts;
It compares what we want from the array and if it is true it will go into the new array. If not then it’s not included.
Don’t forget to put in the return statement.
Be careful of not doing an if statement and then return true because it’s an extra step might as well just return the product of the expression. No need to produce an if statement.
More Complex example. 
Our products array now has a quantity and a price.
var products = [
    {name: ‘cucumber’, type: ‘vegetable’, quantity: 0, price: 1},
    {name: ‘banana’, type: ‘fruit’, quantity: 10, price: 15},
    {name: ‘celery’, type: ‘vegetable’, quantity: 30, price: 10},
    {name: ‘orange’, type: ‘fruit’, quantity: 3, price: 5}
];
We want to only keep items that are a vegetable that have a quantity greater than zero and whose price is less than 10. This is a  multiple filter like we would do on a clothing store.
products.filter(function(product) {
    return(product.type === ‘vegetable’ 
        && product.quantity > 0 
        && product.price < 10);
});
Filter is one of the easier methods to see how it makes our code a bit cleaner and less typing. 

Leave a comment