Skip to main content

Command Palette

Search for a command to run...

Arrays in JavaScript (A masterclass)

Master essential array methods and take your skills to the next level

Published
•13 min read•View as Markdown
Arrays in JavaScript (A masterclass)

Overview of JavaScript Arrays

JavaScript has several data structures for storing and manipulating data. However, when we need an ordered collection of data from the 1st to the 2nd, to the 3rd element, and so on, JavaScript arrays are the most appropriate. Arrays can be used to store a list of items such as accounts, products, HTML elements, and more.

In this article, we'll explore the basics of JavaScript arrays. We'll cover how to create and initialize arrays, how to add, remove, and modify elements, and how to perform common operations like sorting and searching. Additionally, we'll look at real-world use cases and best practices for working with arrays.

What is an array?

An array is a special variable, which can hold one or more values. Arrays can hold as many values as you want and can also hold values of any kind(i.e any data type).

We can say that an array is a big shopping basket in which we throw in different items to be used later.

Why should you even use arrays?

Arrays are very helpful when dealing with data. Some reasons for using arrays are;

  1. Storing collections of data:

    Arrays store collections of data in a single variable, this makes it easy to manage and manipulate data in a program. For example, an array can store a list of names, a set of numbers, or a collection of objects.

  2. Accessing and modifying elements:

    They allow you to access and modify individual elements by using their index values. This makes it easy to perform operations on specific elements in the array, such as sorting, searching, or filtering.

  3. Iterating over elements:

    Arrays provide a convenient way to iterate over all the elements in the array using loops or array methods like forEach, map, filter, and reduce. This makes it easy to perform operations on every element in the array, such as computing the sum of all the numbers or formatting all the strings in a certain way.

Syntax

There are two syntaxes for creating a new empty array, and they are;

const arr = [];
const arr = new Array();

In most cases, we use the first syntax.

Now, let's create a new array and supply initial values to it.

const tools = ["book", "pencil", "coffee"];

So, you see! the two square brackets are basically the shopping basket and we put the items inside it.

Array Methods

Overview of Array Methods

JavaScript array methods make working with arrays easier and a lot more interesting. There are many array methods and they all have their functions. We will cover just enough to make you understand how to work with arrays better.

What are Array Methods?

In JavaScript, array methods are built-in functions that can be used to manipulate arrays. They allow you to perform a variety of operations on arrays, such as adding or removing elements, sorting, filtering, and mapping.

Categorization of Array Methods

To help you understand and use these array methods more effectively, we will group them into the following categories based on functionality;

  1. Adding and removing elements

  2. Searching for elements

  3. Iterating over elements

  4. Transforming the array

Adding and removing elements

Let's discuss array methods that add and remove items from the beginning or the end;

  1. push()

    This method adds one or more elements to the end of the array. I like to see it as pushing items into my grocery shopping basket.

     const fruits = ["Banana", "Orange"];
     fruits.push("Apple"); 
     console.log(fruits); // ["Banana", "Orange", "Apple"];
    

    Return:

    This array method returns the new length of the array after the element/elements have been added.

  2. pop()

    This method removes the last element added from the end of the array. I visualize this as popping off the last item that was added to my basket.

     const fruits = ["Banana", "Orange", "Apple"];
     fruits.pop();
     console.log(fruits) //["Banana", "Orange"]
    
     const itemRemoved = fruits.pop();
     console.log(itemRemoved); // ["Apple"]
    

    Return:

    This method returns that element that was removed.

  3. shift()

    This method is similar to the pop method, but it extracts the first element instead. Yeah, you guessed right, popping off the first item in the basket.

     const fruits = ["Banana", "Orange"];
     fruits.shift();
     console.log(fruits); //["Orange"]
    

    Return:

    This method returns the element that was removed.

  4. unshift()

    This method adds one or more elements to the beginning of the array.

     const fruits = ["Orange"];
     fruits.unshift("Watermelon");
     console.log(fruits); // ["Watermelon","Orange"]
    

    Return:

    This method returns the new length of the array.

  5. splice()

    The splice method can; remove, insert, and replace elements in an array.

    Syntax

     array.splice(start[, deleteCount, elem1, ..., elemN]);
     // note the square brackets only show that those parameters are optional 
    
     array.splice(start, deleteCount, elem1, ..., elemN);
    

    Here's a breakdown of the syntax:

    we modify the array array starting from the index position start and delete deleteCount number of elements, and can optionally insert elem1, ..., elemN in their place.

    Using the splice method:

    1. to remove;

for this, splice() method needs at least one parameter, which is the start index where the splice operation starts.

    const myLove = ["I", "love", "JavaScript"];

    myLove.splice(0, 1); // means: from index 0 remove 1 element

    console.log(myLove); // ["love", "JavaScript"]
  1. to replace;

The splice method also allows you to remove elements and replace them. You just need to pass the elements you want to add to the array after the delete count parameter.

    const adventure = ["I", "love", "JavaScript", "to", "the", "moon"];

    // remove 3 first elements and replace them with another
    arr.splice(0, 3, "Let's", "go", "together");

    alert( arr ) // now ["Let's", "go", "together", "to", "the", "moon"]
  1. to insert;

You can insert new elements in the array without removing any by simply using 0 as the deleteCount parameter.

    const adventure = ["I", "love", "JavaScript"];

    // from index 2
    // delete 0
    // then insert "complex" and "language"
    adventure.splice(2, 0, "beautiful", "language");

    console.log(adventure); // "I", "love", "beautiful", "language", "JavaScript"

Note:

If you don't add, remove or replace any elements, splice() returns an empty array.

  1. slice()

    This method is used to extract a section of an array, it creates a new array containing the extracted items. I take it as slicing your cake and still having the full cake intact

    Syntax

     array.slice([start], [end]);
    

    Here's a breakdown of the syntax:

    The slice method returns a new array array copying all the items from the index start to end(not including item at index end).

    Both start and end can be negative, in that we start counting the index from the end of the array.

    Examples

     const fruits = ["Watermelon","Orange"];
     const slicedFruit = fruits.slice(0, 1);
     console.log(slicedFruit); // ["Watermelon"] it copied from 0 to 1 (remember, not including 1)
    
     const sliceEnd = fruits.slice(-1);
     console.log(sliceEnd); // ["Orange"]
    

    Returns:

    This method returns a new array with the extracted elements.

  2. concat()

    This method is used to merge two or more arrays and returns a new array, without changing the existing arrays.

    It accepts any number of arguments – either arrays or values.

    Syntax

     array.concat(arg1, arg2...)
    

    Return:

    This method returns a new array containing items from array, then arg1, arg2 etc.

    Examples;

     const fruits = ["Watermelon","Orange"];
    
     // create an array from: fruits and ["Apple", "Mango"]
     const newFruits = fruits.concat(["Apple", "Mango"]) );
     console.log(newFruits); // ["Watermelon", "Orange", "Apple", "Mango"]
    
     // create an array from: fruits and ["Apple", "Mango"] and ["Banana", "Pear"]
     const newFruits2 = fruits.concat(["Apple", "Mango"], ["Banana", "Pear"]) );
    
     // create an array from: fruits and ["Apple", "Mango"], then add values "Banana", "Pear"
     const newFruits3 = fruits.concat(["Apple", "Mango"], "Banana", "Pear");
    

Searching for elements

The methods we will cover now, are used to search in an array;

  1. indexOf and lastIndexOf

    • indexOf

the indexOf looks for searchElement starting from index fromIndex, and returns the index where it was found, or-1 if not found.

Syntax

    javascript array.indexOf(searchElement[, fromIndex]);

For example;

    const fruitBasket = ["apple", "banana", "orange", "banana", "mango"];

    fruits.indexOf("banana"), // returns 1, because index position 1 is the first occurence of `banana`

now, let's search for an item that is not in the array

    fruitBasket.indexOf("pineapple") // returns -1, because the `pinneaple` was not found in the array

we can also specify the position where we want the search to begin from

    fruitBasket.indexOf("banana", 2); // returns 3, because the first occurrence of 'banana' after index position 2 is at index position 3 in the array.

Return:

This method returns the index of the first occurrence of a specified value in an array, or -1 if the value is not found.

  • lastIndexOf

This method is the same as the indexOf method, but it looks from right to left.

    const fruitBasket = ["apple", "banana", "orange", "banana", "mango"]; fruitBasket.lastIndexOf("banana"); // returns 3
  1. includes()

    If we want to check if an item exists in the array, and don’t need the index, then the includes method is preferred.

    Syntax

     array.includes(value);
    
     fruitsBasket.includes("apple"); // returns true
     fruitsBasket.includes("cashew"); // returns fakse
    

    Return:

    This method returns true if the array has value, otherwise false.

  2. find() and filter()

    • find()

This method searches for the first element in an array that satisfies a given condition specified by a callback function

Syntax

    array.find(callback(element, index, arr) ,thisArg);
    // index, arr, thisArg are optional

Example;

    const numbers = [1, 2, 3, 4, 5];

    const evenNumber = numbers.find((number) => number % 2 === 0);

    console.log(evenNumber); // Output: 2

Return:

This method returns the value of the first matching element and stops searching after that.

  • filter()

This method creates a new array with all the elements that pass the conditions in the provided callback function. It sieves out the elements that pass the condition you specified.

Syntax

    array.filter(callback(element, index, arr), thisArg)
    // index, arr, thisArg are optional

Example;

    const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    const evenNumbers = numbers.filter((number) => {
      return number % 2 === 0;
    });

    console.log(evenNumbers); // [2, 4, 6, 8, 10]

the callback function inside the filter method adds the elements which satisfy the condition( number % 2 === 0) into the evenNumbers array.

Note;

number % 2 === 0 checks if the remainder of dividing number by 2 is equal to 0

Return:

This method returns a new array containing all the elements of the original array that pass a certain condition specified by a callback function. If no element passes the condition, then an empty array is returned.

  1. findIndex()

    The findIndex() method works similarly to the find method, but instead, it returns the index of the first element that satisfies the condition in the call-back function.

    Syntax

     array.findIndex(function(element, index, arr), thisValue)
     // index, arr, thisArg are optional
    

    Example;

     const numbers = [1, 2, 3, 4, 5];
    
     const evenNumberIndex = numbers.findIndex((number) => number % 2 === 0);
    
     console.log(evenNumberIndex); // Output: 1
    

    Return:

    This method returns the index position of the first element in the array that satisfies the condition in the callback function, in this case, the position is 1.

Iterating over elements

  1. forEach()
  • The forEach method executes a callback function for each element in an array in order.

    Syntax

      array.forEach(function(currentValue, index, arr) {
        // code to be executed for each element
      }, thisValue);
    

    Example;

      const fruitBasket = ["apple", "banana", "orange", "banana", "mango"];
    
      fruitBasket.forEach(function(fruit) {
        console.log(fruit);
      });
    

    from the example above, the function passed to forEach simply logs the current fruit to the console. The forEach method iterates over each fruit in the fruitBasket array and calls the provided function for each element.

    Return

    This method does not return anything.

Transforming the array

  1. map()

    This method creates a new array from the results of calling a function on every element in the array.

    Syntax

     array.map((currentValue, index, array) => {
       // function code here
     });
    

    Now, I want you to understand it in simple English

    (dedicated this part to my friend, Ley)

    Imagine that you have a bunch of Transformer toys, and you want to make them stronger by adding more power to them.

    So, you create a plan(function) to add some extra power to each Transformer toy, but you don't want to change the original toys.

    Instead, you create a new set of toys that are just like the old ones but with extra power added.

    Just like how you created new Transformer toys that were just like the old ones but with extra power, the map() method creates a new array that has the same number of elements as the original array, but each element has been transformed in some way.

    Let's write it as code;

     const transformers = ["Optimus Prime", "Bumblebee", "Megatron", "Starscream"];
    
     const powerfulTransformers = transformers.map((transformer) => `Thundering ${transformer}`);
    
     console.log(powerfulTransformers);
     // Output: ["Thundering Optimus Prime", "Thundering Bumblebee", "Thundering Megatron", "Thundering Starscream"]
    
  2. sort()

    The sort method sorts the elements in an array. It sorts elements in ascending order based on their Unicode character by default. You can provide a comparison function to the sort method to customize the sorting order

    Syntax

     array.sort([compareFunction])
    

    Example;

     const fruits = ["banana", "orange", "apple", "mango"];
     fruits.sort();
     console.log(fruits); // Output: ["apple", "banana", "mango", "orange"]
    

    Return;

    This method returns the sorted array(mutates the original array)

  3. reverse()

    This method reverses the order of elements in an array.

    Syntax;

     arr.reverse();
    

    For example;

     let arr = [5, 4, 3, 2, 1];
     arr.reverse();
    
     console.log(arr); // outputs, 1,2,3,4,5
    

    Return:

    This method returns the array arr after the reversal.

  4. reduce() and reduceRight()

    reduce()

    The reduce method calculates a single value based on an array by calling a function func for each element and passing an intermediate result between the calls

    This means the reduce method keeps track of a value as it iterates over the array and performs the callback function on each element.

    Syntax

     array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
    
     // total – result of the previous function call, equals initialValue the first time (if initialValue is provided).
     // currentValue – current array item.
     // currentIndex(optional) – position.
     // arr(optional) – array itself 
     // initialValue - starting value if first time, total if it is not first time
    

    The function you pass to reduce method performs some operation using these two arguments and returns the result, which becomes the new accumulator for the next iteration.

    This process continues until all elements of the array have been processed, at which point the final accumulator value is returned.

    Example;

     const numbers = [1, 2, 3, 4, 5];
    
     const sum = numbers.reduce((total, currentValue) => total + currentValue, 0);
    
     console.log(sum); // outputs, 15
    

    In the example above, the reduce method takes an initial value of 0, then adds each element of the array to the running total. Finally, it returns the total sum of all the elements in the array.

    Return:

    This method returns a single value that is the accumulated result of iterating through an array.

    Best Practices for Working with Arrays

    Learning from these best practices will make working arrays much more efficient and interesting.

    1. Use descriptive variable names:

Use names that accurately reflect the data they contain. This will make your code more readable and easier to understand.

  1. Use array methods:

Whenever possible, use these methods instead of manually iterating over the array.

  1. Be mindful of array mutations:

Some array methods, such as push(), pop(), shift(), and unshift(), modify the original array. If you don't want to modify the original array, use non-mutating methods like slice(), concat(), or filter().

  1. Use the spread operator to copy arrays:

To create a copy of an array, use the spread operator (...). This is more concise than using the slice() method.

Conclusion

In this blog post, we learnt a lot about arrays. We covered in-depth from what arrays are, to the categories of array methods based on functionalities such as;

  1. Adding and removing elements

  2. Searching for elements

  3. Iterating over elements

  4. Transforming the array

You also learnt about some best practices to consider when working with arrays. Now that you have a good understanding of these concepts, keep practicing and sharing your knowledge with others.

You can connect with me on twitter and follow for more contents like this. See you next time!

Cover Image Credit: JJ YingUnsplash