Javascript Basics - Looping Over Array - Filter Method

Looping Over Array Using Filter Method in a Javascript Object

Usage: Copy and paste the code below into a .html page on your local server and call the page. From there you'll need to open the Devtools (or whatever panel your browser uses) so that you can display and interact with the Javascript console. The code is commented to help you understand as much as possible, so be sure to utilize the comments in context, it will help everything make better sense.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Javascript test document</title>
    
    <script>
    
    // JavaScript Document

    //Transcribed from www.youtube.com/watch?v=BMUiFMZr7vk&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84 

    //var today = new Date();
    //console.log('Today is : ' + today);


    /*
    let countDownFrom = (num) => {
        if (num ===0) {
            return ; 

        console.log(num);

        countDownFrom(num-1);	
        }
    }

    countDownFrom(10);
    */

    /*
    create a variable and assign it an anonymous function
    var triple=function(x) {
        return x*3;
    }

    var waffle = triple; 

    console.log(waffle(30));
    */

    /*
        a simple FOR loop in JS, then the filter method of the array object
        first the generic loop
    */
    
    var animals = [
        {name: 'Alpha', species: 'rabbit'},
        {name: 'Beta', species: 'dog'},
        {name: 'Delta', species: 'dog'},
        {name: 'Harold', species: 'fish'},
        {name: 'Gamma', species: 'cat'},
        {name: 'Sal', species: 'tapeworm'}
    ];

    /*this is the "long" way; manually creating a loop construct, doing the check and then pushing the match to the end of the new dogs array*/
    var dogs = [];

    for (i=0; i<animals.length; i++) {
        if (animals[i].species === 'dog')
            dogs.push(animals[i]);
    }
    

    /*this is the shorter, more efficient 'functional programming way'; the filter method loops through animals[] and sets up the callback function to add the animal if species is 'dog'*/
    
    var dogs = animals.filter(function(animal){
        return animal.species === 'dog';
    });

    console.log('from filter ' + dogs);

    /*Since functional programming makes for better composition, we can break out functionality into smaller parts for possible reuse later on....*/

    var isDog = function(animal){
        return animal.species === 'dogs';
    }

    var dogs = animals.filter(isDog); 

    </script>
    </head>
    <body>
    </body>
    </html>
    

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/javascript/javascript-basics-looping-over-array-filter-method/
Copyright 2018. All Rights Reserved.