Arrays with JavaScript

Arrays with JavaScript

Arrays are the simplest data structures in computer science and problem-solving. Mastering the use of arrays as a software engineer is an important step to honing your problem-solving skills. In this chapter, we will learn the fundamentals of arrays in computer science, using JavaScript.

Arrays store data of the same data type sequentially in memory. Although JavaScript supports data of different data types being stored in an array, it is however considered best practice to store only data of the same data types in an array, as other programming languages do not support this.

Benefits of using Array

Consider a scenario where we store the time taken in minutes for bus X to complete each trip to destination Y.

This will be written in code as:

const time_taken_for_trip1 = 60;

const time_taken_for_trip2 = 58;

const time_taken_for_trip3 = 40;

const time_taken_for_trip4 = 50;

const time_taken_for_trip5 = 55;

This is however not the best approach, as this leads to redundant and repetitive code. This doesn’t seem to be an issue if we only intend to store the records for a few trips. However, this becomes inefficient when trying to store the record of hundreds or thousands of trips. The above record can be stored in an array as shown below

const trip_records = []; //Declare an empty array

trip_records[0] = 60; // Add an element to the array at index position 0

trip_records[1] = 58; // Add an element to the array at index position 1

trip_records[2] = 40; // Add an element to the array at index position 2

trip_records[3] = 50; // Add an element to the array at index position 3

trip_records[4] = 55; // Add an element to the array at index position 4

Or

const trip_records = [60, 58, 40, 50, 55]; //Declare an array and initialise its elements immediately

Declaring and Initializing Arrays

There are two major ways of creating arrays in Javascript, which are;

  • The new Array() constructor: The new Array() constructor is used to create array objects. It takes two optional arguments, which are either the length of the new array object or the elements of the array to be created. If a single numerical argument is passed to the new Array() method, JavaScript interprets this as the length of the array to be created. However, if multiple comma-separated arguments are passed to the new Array() method, JavaScript interprets them as the elements of the array to be created. This is illustrated in the code below.

      const trip_records = new Array(); // An empty trip_records array 
    
      const trip_records = new Array(5); // An empty trip_records array whose length is 5
    
      const trip_records = new Array (60, 58, 40, 50, 55); // trip_records array declared and initialized with its elements immediately
    

However, the above method isn't considered the best practice. The literal notation is considered a more efficient method

  • The Array literal notation: An array literal is a list of comma-separated expressions enclosed in a pair of square brackets []. When an array is created using an array literal, it takes the comma-separated expressions as its elements and the number of expressions added as its length.

      const trip_records = []; // An empty trip_records array whose length is 0
    
      const trip_records = [60, 58, 40, 50, 55]; // trip_records array declared and initialized with its elements immediately, whose length is 5
    

Accessing Elements of An Array

To access the elements of an array, the index of the element in the array is passed into square brackets as shown below

trip_records[0] // 60
trip_records[1] // 58

It is important to note that arrays are 0 indexed, that is, the first element of an array has an index of 0 and not 1 hence the index of the last element in an array would be 1 point less than the length of the array. In the case of the trip_records array, 55 has an index of 4 and the length of the array is 5.

To print all the elements of an array, a simple loop can be used as shown in the code snippet below

for(let i = 0; i < trip_records.length; i++){
    console.log(trip_records[i]);
} 
/*
60
58
40
50
55
*/

Adding Elements To An Array

Adding elements to arrays is one of the major operations that are carried out on arrays. For this exercise, we would initialize an array x as shown below,

const x = [1,2,3,4,5]

Adding elements to the end of the array

JavaScript arrays have a method called push which allows one or more elements to be added to the end of the array upon which it is called. If we want to add 6 to the end of the x array above, the push method will be used as shown in the code below.

console.log(x); // [1,2,3,4,5]

x.push(6);

console.log(x); // [1,2,3,4,5,6]

The code below illustrates adding multiple elements to the end of the array x above.

console.log(x); // [1,2,3,4,5,6]

x.push(7,8,9,["John", "Doe"])

console.log(x); // [1,2,3,4,5,6,7,8,9,["John", "Doe"]]

The time complexity of this operation is O(1) because it takes a single step to add an element to the end of an array, as the operation does not involve moving elements forward or backwards in memory.

Adding elements to the beginning of an array

The unshift method of the JavaScript arrays is used to add elements to the beginning of arrays. If we want to add 0 to the beginning of the array x above, the unshift method will be used as shown in the code below.

console.log(x); // [1,2,3,4,5,6,7,8,9,["John", "Doe"]]

x.unshift(0);

console.log(x); // [0,1,2,3,4,5,6,7,8,9,["John", "Doe"]]

The code below illustrates adding multiple elements to the end of the array x above.

console.log(x); // [0,1,2,3,4,5,6,7,8,9,["John", "Doe"]]

x.unshift(-3,-2,-1,["Positive", "Integers"]);

console.log(x); // [-3,-2,-1,["Positive", "Integers"],0,1,2,3,4,5,6,7,8,9,["John", "Doe"]]

It is important to note that adding elements to the beginning of an array involves more computing processes. Recall that elements of an array are stored sequentially in memory. That is, if 1 above is stored at in-memory address 1000, 2 will be stored at in-memory address 1001 and 5 will be stored at in-memory address 1005. Hence, if we want to add elements to the beginning of the x array, every other element of the array has to be moved forward in memory, to create enough vacant memory at the beginning of the array for new elements to be added. Hence the time complexity of adding elements to the beginning of an array is O(n) where n is the number of elements that need to be moved in memory for the new element/elements to be added.

Removing Elements from an Array

Removing elements from an array is another major operation that is carried out on an array. For this exercise, we would initialize an array x as shown below,

const x = [1,2,3,4,5]

Removing elements from the end of an array

The pop method of the JavaScript arrays allows us to remove the last element in an array as shown in the code below.

console.log(x); // [1,2,3,4,5]

x.pop();

console.log(x); // [1,2,3,4]

The time complexity of this operation is O(1) because it takes a single step to remove the element at the end of the array, as the operation does not involve moving elements forward or backwards in memory.

Removing elements from the beginning of an array

The shift method of the JavaScript arrays allows us to remove the first element in an array as shown in the code below

console.log(x); // [1,2,3,4]

x.shift();

console.log(x); // [2,3,4]

It is important to note that removing elements from the beginning of an array involves more computing processes. Recall that elements of an array are stored sequentially in memory. Hence, if we want to remove an element from the beginning of the x array, every other element of the array has to be moved backwards in memory, to occupy the first vacant memory address. Hence the time complexity of removing elements from an array is O(n) where n is the number of elements that need to be moved in memory for the element to be removed.

Adding and Removing Elements from Specific Positions in an Array

Now we know how to add an element to the end and beginning of an array, and also how to remove an element from the beginning and end of an array. However, adding and removing elements from specific positions in an array is another major operation which is performed on arrays.

The splice method of the JavaScript arrays allows us to add elements to and remove elements from an array at specific positions. It takes 2 compulsory and 1 optional argument. The first argument specifies the index at which our operation should begin. The second argument is used to specify the number of elements we wish to remove from an array (0 is passed if we do not wish to remove any element). The third optional argument(s) is the element/elements we wish to add to the array. The use of the splice method is illustrated with the following examples.

For this exercise, we would initialize an array x as shown below,

const x = [0,1,2,3,4,5,6,7,8,9]

Removing elements using the splice method

We can remove elements using the splice method by specifying the index which we want to start removing from, and the number of elements we want to remove. This is illustrated in the code below

console.log(x); // [0,1,2,3,4,5,6,7,8,9]

x.splice(2,3);

console.log(x); // [0,1,5,6,7,8,9]

Similar to removing elements from the beginning of an array, the time complexity of this operation is O(n). Where n is the number of elements that need to be moved in memory for the element to be removed.

Adding elements to an array using the splice method

Suppose we want to add elements 2,3,4 back to the x array, the splice method can be used as illustrated below.

console.log(x); // [0,1,5,6,7,8,9]

x.splice(2,0,2,3,4);

console.log(x); // [0,1,2,3,4,5,6,7,8,9]

The first argument 2 passed to the splice method is used to specify the index where our operation will begin. The second element 0 specifies the number of elements we wish to remove from the array. 2,3,4 are the elements we wish to add to the array.

Similar to adding elements to the beginning of an array, the time complexity of this operation is O(n). Where n is the number of elements that need to be moved in memory for the new element/elements to be added.

The code below illustrates how to remove and add elements to an array simultaneously using the splice method.

console.log(x); // [0,1,2,3,4,5,6,7,8,9]

x.splice(3,3,10,20)

console.log(x); // [0,1,2,10,20,6,7,8,9]

The time complexity of this operation is O(n).


Congratulations on getting here, in this chapter, we have learnt why we use arrays, how to declare and initialize arrays, how to access elements in an array, how to add elements to an array and how to remove elements from an array. In the next chapter of this series, we will dive deeper into the world of arrays, learning about two-dimensional and multi-dimensional arrays, and JavaScript array methods among other things.