Example

Array Methods - Part-2

HTML

<!DOCTYPE html>
<html lang="en-US">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link name="favicon" type="image/x-icon" href="https://skillzam.com/uploads/system/e353194f3b7cd1b75d69c3ab88041985.png" rel="shortcut icon" />
    <title>Array Methods - Part-2</title>
    </head> 
<body>
<!--
    forEach() : method is an iterative method. It calls a provided callback function once for each element in an array in ascending-index order.
    map() : method creates a new array populated with the results of calling a provided function on every element in the calling array.
    filter() : method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
    find() : method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
    reduce() : method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
    some() :  method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
    every() : method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
-->

    <h1>Demo: Array Methods - Part-2</h1>

    <div>
        <h2>Array Method: forEach( )</h2>
        <p id="para1"></p>
        <p id="para2"></p>
    </div>

    <div>
        <h2>Array Method : map( )</h2>
        <p id="para3"></p>
        <p id="para4"></p>
    </div>

    <div>
        <h2>Array Method : filter( )</h2>
        <p id="para5"></p>
        <p id="para6"></p>
    </div>

    <div>
        <h2>Array Methods : find( )</h2>
        <p id="para7"></p>
    </div>

    <div>
        <h2>Array Method : reduce( )</h2>
        <p id="para8"></p>
        <p id="para9"></p>
    </div>

    <div>
        <h2>Array Method : some( )</h2>
        <p id="para10"></p>
        <p id="para11"></p>
    </div>

    <div>
        <h2>Array Method : every( )</h2>
        <p id="para12"></p>
        <p id="para13"></p>
    </div>


    <!-- JavaScript code Starts here -->
    <script>

        /************************************************/
        // Array Method: forEach()
        // Example : Array of numbers - Single digit even number
        //
        const singleDigit = [0, 1, 3, 5, 7, 8, 9];
        singleDigit.forEach(function (digit) {
            if (digit % 2 === 0 && digit > 0) {
                document.getElementById('para1').innerHTML = 
                `The Even number in the array "singleDigit" is = ${digit}`;
            }
        })
        // Same as above using 'for of' loop
        // for (let digit of singleDigit) {
        //     if (digit % 2 === 0 && digit > 0) {
        //         document.getElementById('para1').innerHTML = 
        //         `The Even number in the array "singleDigit" is = ${digit}`;
        //     }
        // }


        /************************************************/
        // Array Method :  forEach() 
        // Example : Array of objects - Player Rating
        //
        const playerRating = [
            {
                name: 'Messi',
                rating: 9
            },
            {
                name: 'Ronaldo',
                rating: 8
            },
            {
                name: 'Neymar',
                rating: 7
            },
            {
                name: 'John',
                rating: 6
            }
        ]
        playerRating.forEach(function (player) {
            if (player.rating > 6) {
                document.getElementById('para2').innerHTML = 
                `The rating of ${player.name} = ${player.rating}`;
            }
        })

        
        /************************************************/
        // Array Method : map()
        // Example : Array of numbers - Squaring of odd single digit numbers 
        //
        const oddNum = [1, 3, 5, 7, 9];
        const squNum = oddNum.map(function (value) {
            return value * value;
        })
        document.getElementById('para3').innerHTML = 
        `Square of each element of array "oddNum" is a new array = [${squNum}]`;


        /************************************************/
        // Array Method : map()
        // Example : Array of objects - Hexcode RBG colors
        //
        const hexcodeRGB = [
            {
                color: 'red',
                hexcode: '#FF0000',
                wavelength: 650 
            },
            {
                color: 'green',
                hexcode: '#00FF00',
                wavelength: 550 
            },
            {
                color: 'blue',
                hexcode: '#0000FF',
                wavelength: 450 
            }
        ]
        const newColors = hexcodeRGB.map(function (colorsRGB) {
            if (colorsRGB.wavelength > 500) {
                return colorsRGB.color;
            } else {
                return 'N/A';
            }
        })
        document.getElementById('para4').innerHTML = 
        `The colors with wavelength more than 500 = [${newColors}]`;


        /************************************************/
        // Array Method : filter()
        // Example : Filter Number that are less than 15 
        //
        const tenTwenty = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
        const lessThan15 = tenTwenty.filter(num => {
            return num < 15
        })
        document.getElementById('para5').innerHTML = 
        `New array "lessThan15" contains  = [${lessThan15}]`;


        /************************************************/
        // Array Method : filter()  
        //  Example : Earth Zones
        //
        const earthZones = [
            {
                name: 'Torrid',
                Maxlatitude: 23.5
            },
            {
                name: 'Temperate',
                Maxlatitude: 66.5
            },
            {
                name: 'Frigid',
                Maxlatitude: 90
            }
        ]
        const hotestZone = earthZones.filter(zone => zone.Maxlatitude <= 30);
        console.log(hotestZone);    // console log output    
        document.getElementById('para6').innerHTML = 
        `The Hotest zone on earth  = ${hotestZone[0].name}`;
        

        /************************************************/
        // Array Methods : find()  
        // Example : Find the first word that has more than 3 letters
        //
        const smallWords = ['bat', 'cat', 'mat', 'rat', 'that', 'what'];
        const largeWords = smallWords.find(word => {
            if (word.length > 3) {
                return word;
            }
        })
        document.getElementById('para7').innerHTML = 
        `The first large word in array "smallWords" is  = ${largeWords}`;
    

        /************************************************/
        // Array Method : reduce() 
        // Find the sum of an array elements 
        //
        const prices = [12.25, 24.75, 32.00, 55.25, 76.50];
        const sumPrice = prices.reduce((sum, price) => sum + price);
        document.getElementById('para8').innerHTML = 
        `Sum of all numbers in arrary "prices" is = ${sumPrice}`;

        // // The above can be done using for .. of loop
        // let sumPrice = 0;
        // for (let price of prices) {
        //     sumPrice += price;    // sumPrice = sumPrice + price;
        // }
        // document.getElementById('para8').innerHTML = 
        // `Sum of all numbers in arrary "prices" is = ${sumPrice}`;


        /************************************************/
        // Array Method : reduce() 
        // Example : Find Best Rated player in array of objects
        // 
        const ratePlayers = [
            {
                name: 'Messi',
                rating: 9
            },
            {
                name: 'Ronaldo',
                rating: 8
            },
            {
                name: 'Neymar',
                rating: 7
            },
            {
                name: 'John',
                rating: 6
            }
        ]

        const topRated = ratePlayers.reduce((bestRate, currRate) => {
            if (currRate.rating > bestRate.rating) {
                return currRate;
            }
            return bestRate;
        })
        document.getElementById('para9').innerHTML = 
        `The best rated player is "${topRated.name}" and his rating is "${topRated.rating}" `;


        /************************************************/
        // Array Method : some()   
        // Example : Does any value exits in the array - true/false ?
        //
        const scoredRuns = [312, 278, 301, 277, 498, 189];
        const isExists = scoredRuns.some(run => run > 450);
        document.getElementById('para10').innerHTML = 
        `Is there a score more than 450 in a ODI cricket match ? : ${isExists}`;


        /************************************************/
        // Arrar Method : some()  
        // Example: Has anyone, won Ballon dor more than 6 times ? true/false
        // 
        const  playerBallondor = [
            {
                name: 'Johan Cruyff',
                won: 3
            },
            {
                name: 'Michel Platini',
                won: 3
            },
            {
                name: 'Cristiano Ronaldo',
                won: 5
            },
            {
                name: 'Lionel Messi',
                won: 7
            }
        ]
        const isWon = playerBallondor.some(player => player.won > 6);
        document.getElementById('para11').innerHTML = 
        `Has anyone, won Ballon dor more than 6 times ? : ${isWon}`;


        /************************************************/
        // Array Method : every()   
        // Example : Is every element, a square number in the array ?
        //
        const givenNumbers = [4, 9, 16, 25, 36, 49, 64];
        const isAllSquare = givenNumbers.every(function (num) {
            let elementNum = Math.sqrt(num);
            return (Number.isInteger(elementNum));
        }
        )
        document.getElementById('para12').innerHTML = 
        `Is every element, a square number in the array ? : ${isAllSquare}`;


        /************************************************/
        // Array Method : every()  
        // Example : Is every country, won the FIFA world cup atleast 3 times ?
        //
        const fifaWorldCups = [
            {
                name: 'Italy',
                won: 4
            },
            {
                name: 'Germany',
                won: 4
            },
            {
                name: 'Brazil',
                won: 5
            },
            {
                name: 'Argentina',
                won: 3
            }
        ]
        const isAllCountry = fifaWorldCups.some(country => country.won >= 3);
        document.getElementById('para13').innerHTML = 
        `Is every country, won the FIFA world cup atleast 3 times ? : ${isAllCountry}`;


    </script>   
    <!-- JavaScript code Ends here -->

</body>
</html>    
                                    

Output

View original