Arrays in JavaScript

JavaScript , Mon Jan 02 2023

    Arrays

    In programming, quite often we will need an ordered collection, where we have a 1st, 2nd, 3rd element and so on.

    For example, we need that to store a list of something: users, items, elements etc.

    There exists a special data structure named Array, to store ordered collections.

    Declaration

    This is how we declare an array - the most important part here are the square brackets:

    const months = ['January', 'February', 'March', 'April'];

    Array elements are numbered, starting with zero.

    We can get an element by its number in square brackets:

    console.log(months[0]); // 'January'

    We can replace an element

    months[2] = 'Not March'; // ['January', 'February', 'Not March', 'April']

    …Or add a new one to the array:

    months[4] = 'May'; // ['January', 'February', 'March', 'April', 'May']

    The total count of the elements in the array is its length:

    console.log(months.length); // 5

    An array can store elements of any type:

    const arr = [
        'Apple',
        { name: 'John'},
        true,
        function () {
            alert('Hello');
    },
    ];

    You're often going to find yourself needing to loop through all the elements of an array. That's where the for loop we've learned comes in handy:

    for (let i=0; i < months.length; i++){
    ;     console.log(carr[i]);
    }

    Later, I've dedicated a few whole lectures about different built in array methods for looping. They allow us to loop faster, with added functionality and less code.

    Array Methods

    Aside from containing variables at indexes, an array contains a variety of premade functions with which you can manipulate it's data, like adding or removing elements at certain positions! Let's take a look at a few of the most basic ones right now.

    array.push(value)

    The array.push() function adds a new element, containing the entered variable, to the end of the array.

    const names = ['Jon', 'Bob', 'David', 'Mark'];
    names.push('Dean');
    console.log(names); // ["Jon", "Bob", "David", "Mark", "Dean"]

    There's one important thing that many experienced web developers don't know about array.push(). What's it's the return value?

    Many would think that the return value of the push would be an array, now including the element we've pushed. Let's test it out:

    console.log(names.push('Dean')); // 5

    The return value is 5. Hmm, why 5? Think about it.

    It turns out that the array.push() returns the length of the array when the element is pushed.

    We can even store it in a variable:

    const length = names.push('Dean');
    console.log(length); //5

    array.pop()

    The array.pop() function on the other hand, does quite the opposite, deleting the last element of an array.

    const names = ['Jon', 'Bob', 'David', 'Mark'];
    names.pop();
    console.log(names); //["Jon", "Bob", "David"]

    This time, the return of the method is not the final length of the array, as it is with array.push(), rather, it's the value of the removed element. You have it in case you need it somewhere.

    const removedValue = names.pop();
    console.log(removedValue); // "Mark"

    This can be great for transferring data between two arrays or just giving a value one final use before popping it into the void.

    array.shift()

    Shift works almost exactly like pop, with one major difference. It deletes the first value in an array and moves the rest backwards!

    const names = ['Jon', 'Bob', 'David', 'Mark'];
    names.shift();
    console.log(names); //["Bob", "David", "Mark"]

    It too returns the "popped" value.

    const removedValue = names.shift();
    console.log(removedValue); // "Jon"

    array.unshift(value)

    If shift is the sister function to pop, unshift is that to push. It adds a new value to the start of an array instead of the end!

    const names = ['Jon', 'Bob', 'David', 'Mark'];
    names.unshift('Dean');
    console.log(names); //["Dean", "Jon", "Bob", "David", "Mark"]

    Much like push, it returns the new array length.

    It too returns the "popped" value.

    const length = names.unshift('Dean');
    console.log(length); // 5

    array.splice()

    Now this one is a little more sophisticated, but don't worry we'll walk you through it.

    The splice method allows you to "splice" values into the array. It's first parameter determines where the new element or elements are placed, the second how many after that point should be deleted before placement and each subsequent condition is merely an element you wish to add.

    Here's an example.

    const names = ['Jon', 'Bob', 'David', 'Mark'];
    names.splice(2, 0, 'Jenny', 'Johnny');
    console.log(names); // ["Jon", "Bob", "Jenny","Johnny", "David", "Mark"]

    It can also return an array of any deleted items, like pop!

    const removedValue = names.splice(0, 1);
    console.log(removedValue); // ["Jon"]

    array.slice()

    And finally, the slice function. This handy little piece of code can make a new variable that contains every element from a certain point on in whatever array you feed it!

    const names = ['Jon', 'Bob', 'David', 'Mark'];
    const noOneLikesJson = names.slice(1);
    console.log(noOneLikesJson); // ["Bob", "David", "Mark"]

    Don't worry, Jon is still in the first array.

    console.log(names); // ["Jon", "Bob", "David", "Mark"]

    • array[index]: array[index]
    • push(value): adds the value to the end of the array
    • pop(): removes the value from the end of the array
    • shift(): removes the value from the start of the array
    • unshift(value): adds the value to the start of the array
    • splice(fromIndex, no_of_elements): removes the number_of_elements, starting from fromIndex from the array
    • slice(fromIndex, toIndex): copies a certain part of the array
    • concat(): Join several arrays into one
    • join(''): returns a string of array values
    • array.length: returns the number of elements in the array
    • reverse(): reverse the order of the elements in an array
    • toString(): returns a string representing the specified array and its elements.
    • includes(searchElement): determines whether an array includes a certain value among its entries, returning true or false as appropriate.
    • sort(): It sorts the elements of an array in place and returns the sorted array. It sorts an array alphabetically.
    • indexOf(searchElement): returns the index of the first occurance of that value
    • lastIndexOf(searchElement): returns the index of the last occurance of that value
    • array.slice(): And finally, the slice function. This handy little piece of code can make a new variable that contains every element from a certain point on in whatever array you feed it!

    Array method for looping

    array.forEach()

    It executes a provided function once for each array element.

    array.forEach((element, index) => {
    // code block to be executed
    })
    array.map()

    It creates a new array populated with the results of calling a provided function on every element in the calling array.

    array.map((element, index) => {
    // code block to be executed
    })
    array.filter()

    It creates a new array with all elements that pass the test implemented by the provided function.

    array.filter((element, index) => {
    // code block to be executed
    })
    array.findIndex()

    It returns the index of the first element in the array that satisfies the provided testing function

    array.findIndex((el, idx, arr) => {
    // code block to be executed
    })
    array.some()

    It tests whether at least one element in the array passes the test implemented by the provided function

    array.some((el, index, array)) => {
    // code block to be executed
    })
    array.every()

    It tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

    array.every((element, index) => {
    // code block to be executed
    })
    array.reduce()

    It runs a function on each array element to produce (reduce it to) a single value. It works from left-to-right.

    array.reduce((prevValue,currentValue,
    currentIndex, array)) => {
    // code block to be executed
    })
    array.reduceRight()

    It runs a function on each array element to produce (reduce it to) a single value. It works from right-to-left.

    array.reduceRight((accumulator,
    currentValue, index, array)) => {
    // code block to be executed
    })