JavaScript Arrays In detail

javascript Jul 31, 2019

Arrays are one of the most fundamental data structures. If you have ever programmed before, you’ve most likely used an array.

 var array1 = [1,2,3,4];

For any data structure, developers are interested in time and space complexity associated with the four fundamental operations: access, insertion, deletion, and search.

Insertion

Insertion means adding a new element inside a data structure. JavaScript implements array insertion with the .push(element) method. This method adds a new element at the end of the array.

var array1 = [1,2,3,4]; 
array1.push(5); //array1 = [1,2,3,4,5] 
array1.push(7); //array1 = [1,2,3,4,5,7] 
array1.push(2); //array1 = [1,2,3,4,5,7,2]

The time complexity of this operation is O(1) in theory. It should be noted that, practically, this depends on the JavaScript engine that runs the code. This applies to all natively supported JavaScript objects

Deletion

JavaScript implements array deletion with the .pop() method. This method removes the last-added element of the array. This also returns the removed element.

 var array1 = [1,2,3,4]; 
 array1.pop(); //returns 4, array1 = [1,2,3] 
 array1.pop(); //returns 3, array1 = [1,2]

The time complexity of .pop is O(1) similarly to .push. Another way to remove an element from an array is with the .shift() method. This method will remove the first element and return it.

array1 = [1,2,3,4]; 
array1.shift(); //returns 1, 
array1 = [2,3,4] 
array1.shift(); //returns 2, array1 = [3,4]

Access

Accessing an array at a specified index only takes O(1) because this process uses that index to get the value directly from the address in memory. It is done by specifying the index (remember that indexing starts at 0).

 var array1 = [1,2,3,4]; 
 array1[0]; //returns 1 
 array1[1]; //returns 2
 

Iteration

Iteration is the process of accessing each of the items contained within a data structure. There are multiple ways to iterate through an array in JavaScript. They all have a time complexity of O(n) since the iteration is visiting n number of elements.

for (Variables; Condition; Modification)

for is the most common method of iteration. It is most often used in this form

 for ( var i=0, len=array1.length; i<len; i++ ) { 
         console.log(array1[i]); 
     }

The previous code simply means initialize the variable i, check whether the condition is false before executing the body (i<len), and then modify (i++) until the condition is false. Similarly, you can use a while loop. However, the counter will have to be set outside.

  var counter=0; 
    while(counter<array1.length){ 
    // insert code here 
    counter++; 
    }

You can implement an infinite loop using a while loop, as shown here:

  while(true){ 
  if (breakCondition) { 
   break; 
   } 
  }

Similarly, a for loop can implement an infinite loop by not setting a condition, as shown here:

 for ( ; ;) { 
 if (breakCondition) { 
    break 
  } 
 }

for ( in )

Another way to iterate a JavaScript array is to call the indices one by one. The variable specified before in is the index of the array, as follows:

 var array1 = ['all','cows','are','big']; 
   for (var index in array1) { 
          console.log(index); 
       }

This prints the following: 0,1,2,3. To print the content, use this:

 for (var index in array1) { 
    console.log(array1[index]); 
   }

This prints all, cows, are, and big.

for ( of )

The variable specified before of is the element (the value) of the array, as follows:

 for (var element of array1) { 
 console.log(element); 
 }
This prints out all, cows, are, and big.
 

forEach( )

The big difference between forEach and other methods of iteration is that forEach cannot break out of the iteration or skip certain elements in the array. forEach is more expressive and explicit by going through each element.

  var array1 = ['all','cows','are','big']; 
    array1.forEach( function (element, index){ 
          console.log(element);  
      }); 
        array1.forEach( function (element, index){                        console.log(array1[index]);
      })
Both print all, cows, are, and big.
 

Helper Functions


The following sections discuss other commonly used helper functions for processing.  In addition, working with arrays will be covered.

.slice(begin,end)

This helper function returns a portion of an existing array without modifying the array. .slice() takes two parameters: the beginning index and the ending index of the array.

 var array1 = [1,2,3,4]; 
 array1.slice(1,2); //returns [2], array1 = [1,2,3,4] 
 array1.slice(2,4); //returns [3,4], array1 = [1,2,3,4]

If only the beginning index is passed, the ending will be assumed to be the maximum index.

 array1.slice(1); //returns [2,3,4], 
 array1 = [1,2,3,4] 
 array1.slice(1,4); 
 //returns [2,3,4], 
 array1 = [1,2,3,4]

If nothing is passed, this function simply returns a copy of the array. It should be noted that array1.slice() === array1 evaluates to false. This is because although the contents of the arrays are the same, the memory addresses at which those arrays reside are different.

array1.slice(); //returns [1,2,3,4], array1 = [1,2,3,4]

This is useful for copying an array in JavaScript. Remember that arrays in JavaScript are reference-based, meaning that if you assign a new variable to an array, changes to that variable apply to the original array.

 var array1 = [1,2,3,4], 
 array2 = array1; 
 array1 // [1,2,3,4] 
 array2 // [1,2,3,4] 
 
 array2[0] = 5; 
 
 array1 // [5,2,3,4] 
 array2 // [5,2,3,4]

The changing element of array2 changed the original array by accident because it is a reference to the original array. To create a new array, you can use .from().

 var array1 = [1,2,3,4]; 
 var array2 = Array.from(array1); 
 
 array1 // [1,2,3,4] 
 array2 // [1,2,3,4] 
 
 array2[0] = 5; 
 
 array1 // [1,2,3,4] 
 array2 // [5,2,3,4]

.from() takes O(n), where n is the size of the array. This is intuitive because copying the array requires copying all n elements of the array.

.splice(begin,size,element1,element2…)

This helper function returns and changes the contents of an array by removing existing elements and/or adding new elements.

.splice() takes three parameters: the beginning index, the size of things to be removed, and the new elements to add. New elements are added at the position specified by the first parameter. It returns the removed elements

  var array1 = [1,2,3,4]; 
  array1.splice(); //returns [], 
  array1 = [1,2,3,4] 
  array1.splice(1,2); 
  //returns [2,3], array1 = [1,4]

This example demonstrates removal. [2,3] was returned because it selected two items starting from an index of 1.

  var array1 = [1,2,3,4]; 
  array1.splice();
  //returns [], array1 = [1,2,3,4] 
  array1.splice(1,2,5,6,7); //returns [2,3],array1 = [1,5,6,7,4]

Anything (any object type) can be added to the array. This is the beauty (and odd part) of JavaScript.

 var array1 = [1,2,3,4]; 
 array1.splice(1,2,[5,6,7]); //returns [2,3], array1 = [1,[5,6,7],4] 
 array1 = [1,2,3,4]; 
 array1.splice(1,2,{'ss':1}); //returns [2,3], array1 = [1,{'ss':1},4]

.splice() is, worst case, O(n). Similarly to copying, if the range specified is the whole array, each n item has to be removed.

.concat()

This adds new elements to the array at the end of the array and returns the array.

 var array1 = [1,2,3,4]; 
 array1.concat(); //returns [1,2,3,4], array1 = [1,2,3,4] 
 array1.concat([2,3,4]); //returns [1,2,3,4,2,3,4],array1 = [1,2,3,4]
 

.length Property

The .length property returns the size of the array. Changing this property to a lower size can delete elements from the array.

 var array1 = [1,2,3,4]; 
 console.log(array1.length); //prints 
 
 array1.length = 3; // array1 = [1,2,3]
 

Spread Operator

The spread operator, denoted by three periods (...), is used to expand arguments where zero arguments are expected

 function addFourNums(a, b, c, d) { 
 return a + b + c + d; 
 } 
 var numbers = [1, 2, 3, 4]; 
 console.log(addFourNums(...numbers)); // 10

Both the Math.max and Math.min functions take an unlimited number of parameters, so you can use the spread operator for the following operations. To find the maximum in an array, use this:

  var array1 = [1,2,3,4,5]; 
  Math.max(array1); // 5
  
To find the minimum in an array, use this:

   var array2 = [3,2,-123,2132,12]; 
   Math.min(array2); // -123
 

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning