JavaScript Array Methods

An outline of what you'll learn!

First of all, you just need to remember how the keyword this reacts with arrow functions!

In brief, this section will help you to understand the arrow function syntax, as well as the following methods:

Arrows and this

How does this react with arrow functions?

Not particularly well, then within objects! Essentially, when used with an arrow function, the this keyword will REFER TO the scope it was created in! When we use a non-arrow function, the keyword this pay attention to where the function is executed

forEach

This is a little old-fashioned. Put simply, it:

  • Accepts a callback function
  • Calls the function once per element in the array
  • An uncommon example is this! It is MUCH MORE common to define some anonymous function inline, i.e. using nums.forEach(function (element)).

                            
                                const numbers = [1,2,3,4,5];
                                COMMON
                                numbers.forEach(function(element){
                                    console.log(element);
                                })
                                
    
                                UNCOMMON
                                function print(element){
                                    console.log(element)
                                }
                                nums.forEach(print);
                            

    In a nutshell, the forEach() method executes a provided function once for each array element

    Now, for a more complicated example, using players! We want some means of printing out their name and rating in FIFA! The biggest pitall of forEach is the placement of the inline function parentheses!

                            
                                const players = [
                                    {
                                    name:'Lionel Messi',
                                    rating: 95
                                    },
                                    {
                                    name:'Bukayo Saka',
                                    rating: 92
                                    },
                                    {
                                    name:'Pedri',
                                    rating: 90
                                    }
                                ]
    
                                players.forEach(function(player){
                                    console.log(`${player.name} ${player.rating}`);
                                })
                            

    map

    The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

                            
                                const array1 = [1, 4, 9, 16];
    
                                // Pass a function to map
                                const map1 = array1.map(x => x * 2);
    
                                console.log(map1);
                                // Expected output: Array [2, 8, 18, 32]
                            

    More simply, map creates a new array with the results of calling a callback on every element in the array

    Arrow Functions

    A really key part of modern JavaScript: shorthand syntax that defines a function.

    Consists of a fat arrow (=>), which defines the function, rather than the function keyword.

    One rudimentary example is this, which takes in a string and converts it to upper case:

                            
                                const result = (str) => str.toUpperCase();
                                const result = str => str.toUpperCase();  
                                (If we only take 1 parameter, we can choose to keep or omit the parentheses)
                            

    A more advanced example is this, which takes in an array of numbers, returning the largest:

                            
                                const maxNumber = (number) => Math.max(...numbers);
                                //First introduction to the .max function
                            

    Finally, the hardest example is this, which flips around the key and value of an object:

                        
                            const flipped = (object1) => {
                                let newObject = {};
                                for(let key in object1){
                                    newObject[object1[key]] = key;
                                }
                            }
                        

    Another example, and attempting to link .map as well, is going to re-use some old code

                        
                    const players = [
                        {
                        name:'Lionel Messi',
                        rating: 95
                        },
                        {
                        name:'Bukayo Saka',
                        rating: 92
                        },
                        {
                        name:'Pedri',
                        rating: 90
                        }
                    ]
                    const newPESRating = players.map(function(player){
                        return `${player.name}-${player.rating/10}`
                    })
    const newPesRating = players.map((player) =>{ `${player.name}-${player.rating/10}` }) Implicitly returns Lionel Messi-9.5 Bukayo Saka-9.2 etc...

    setTimeout() and setInterval()

    In other programming languages like C++, it's possible to use the sleep(time_period in seconds) function. In JavaScript, we have a function called setTimeout

    setTimeout() allows you to execute a piece of code after a specified amount of time has passed. It's a method of the window object and is commonly used in conjunction with other JavaScript methods and functions to create timed events or delayed actions in web pages.

    The basic syntax is:

                            
                                setTimeout(function, delay);
                                function is the JavaScript function you want to execute after the delay.
                                delay is the time in milliseconds before the function is executed.
                            

    As an example of the above, you could use the following code to display an alert after 2 seconds:

                            
                                setTimeout(() => {
                                    alert("I hate to interrupt, but...");
                                }, 2000);
                            

    It's also important to know that setTimeout returns a timeout ID that can be used to clear the timeout with clearTimeout() function, which prevents the alert message from being displayed!

    It's common to use setTimeout in conjunction with other JavaScript methods and functions, such as setInterval() to create timed events or delayed actions in web pages.

    setInterval() is very similar to setTimeout(), but it repeats execution of the function INDEFINITELY, at a fixed time interval specified in milliseconds.

    The basic syntax of this one is:

                            
                                setInterval(function,delay);
                                function is the JavaScript function you want to execute repeatedly.
                                delay is the time in milliseconds between each execution of the function.
                            

    For example, you could use the following code to display an alert message every 2 seconds:

                        
                            setInterval(() => {
                                alert("I know a line that will get on your nerves...");
                            }, 2000);
                            Executes the above line every 2 seconds... :/
                        

    As with setTimeout, setInterval returns a interval ID that can be used to clear the interval with the clearInterval() function:

                            
                                let intervalId = setInterval(() => {
                                    alert("Hello, World!");
                                }, 2000);
                                
                                clearInterval(intervalId);
                            

    It's important to keep in mind that setInterval() is a powerful tool and should be used with care, as it can cause performance issues if not used properly. For example, if you have a function that takes a long time to execute and is set to run every few milliseconds, it can cause the browser to slow down or crash. You should also be careful when using setInterval() with setTimeout() together, since it can cause unexpected behavior if not used properly. Also, be aware that the actual interval may vary depending on the JavaScript engine, system load and other factors.

    filter

    The filter() method creates a shallow copy (i.e. a copy that shares references pointing to the same underlying values as in the original array) 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.

    As an example, I'll show how to get only the best (well, 7.0+) shows from this array:

                                
                                    const retroShows = [
                                    {
                                        title:'Sister Sister',
                                        score:6.3,
                                        year:1994
                                    },
                                    {
                                        title:'Alex Mack',
                                        score:7.5,
                                        year:1994,
                                    }
                                    ];
                                    const bestOnes = retroShows.filter(show => show.score >= 7.0);
                                

    My apologies to Sister Sister!

    find

    The 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

    This is the toughest of all the functions! It allows us to reduce all elements in an array to a single value.

    This can be used to find the total sum of an array, or a min/max value, and so on!

    As an example, look at this code:

                            
                                const prices = [9.99,5.99,6.99];
                                const total = prices.reduce((total,price) => {
                                    return total+price;
                                })
                            

    The syntax is fairly easy. Essentially, in this function, prices.reduce((total,price), the part in parentheses (and bold) is called the reducer function. The first parameter is some type of accumulator (labelled 'total' here), and the second parameter represents EACH individual element in the array.

    So, using const total = nums.reduce((accumulator, element)=>{return accumulator+total}); should give you a nice alternative to using a for-loop to get a total from an array!

    Another example uses players again:

                            
                                const players = [
                            {
                                name:'Lionel Messi',
                                rating: 95
                                },
                                {
                                name:'Bukayo Saka',
                                rating: 92
                                },
                                {
                                name:'Pedri',
                                rating: 90
                                }
                            ]
    
                            let highestRatedPlayer = players.reduce((bestPlayer,curPlayer) => {
                                if(curPlayer.rating > bestPlayer.score)
                                    return curPlayer;
                                return bestPlayer;
                            }
                            

    We can also set an initial starting point for things:

                            
                                const evens = [2,4,6,8];
                                evens.reduce((sum,num)=>sum+num, 100)
                            

    some

    Like every(), this returns a boolean value. This function will return true is ANY of the array elements pass the test function.

                                
                                    function containsStinker(element, index, array) {  //index and array can be omitted!
                                        return element <= 5.0;
                                      }
                                      [9.2, 8.3, 6.4, 1.3, 9.1].some(containsStinker); // true
                                      [7.0, 8.5, 9.0, 8.9, 7.9].some(containsStinker); // false
                                

    every

    Like some(), this returns a boolean value. The every() method tests whether ALL elements in the array pass the test implemented by the provided function.

                                
                                    function isBigEnough(element, index, array) {  //again, index and array can be omitted!
                                        return element >= 10;
                                      }
                                      [12, 5, 8, 130, 44].every(isBigEnough); // false
                                      [12, 54, 18, 130, 44].every(isBigEnough); // true
                                

    So, for example, is EVERY movie in your list ranked 8.0+ on IMDB. Are ALL (every ;)) test scores in the class higher than 70?

    Newer Aspects of JavaScript

    • Default parameters are fairly easy to understand! You've used things like void dfs(...int parentRow = -1, int parentCol = -1) in C++. In JavaScript, default parameters just involved assigning some parameter with a specific value/number/string. That way, we can avoid unwanted problems, such as a value being undefined, or no argument being sent to a parameter that is begging for one! As in C++, the default parameters should be further to the right of any signature!