JS Arrays

Welcome to another tutorial, here you will learn to create and manipulate arrays in JavaScript.

 

What is an Array

JavaScript arrays as complex variables allow more than one value or a group of values stored under a single variable name. It stores any valid value, encompassing strings, numbers, objects, functions, and even other arrays, hence making it possible to create more complex data structures such as an array of objects or an array of arrays.

To store the name of colors in a variable in your JavaScript code could look something like this:

var color1 = "Red";
var color2 = "Green";
var color3 = "Blue";

But to store the state or city names of a country in variables that may be a hundred in a separate variable is quite hard and boring. Hence, it will be a herculean task to keep track of many variables simultaneously. In this case, the array comes into play and solves the problem by providing an ordered structure for storing a group of values or multiple values.


Creating an Array

In JavaScript, enclosing a comma-separated list of values in square brackets ([]), as shown in the following syntax is the simplest way of creating an array.

var myArray = [element0, element1, ..., elementN];

To create an array, the Array() constructor as shown in the following syntax can be used. But, the previous syntax is recommended for the sake of simplicity. 

var myArray = new Array(element0, element1, ..., elementN);

Here are some examples of arrays created using an array literal syntax:

var colors = ["Red", "Green", "Blue"]; 
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var cities = ["London", "Paris", "New York"];
var person = ["John", "Wick", 32];

Note: An ordered collection of values is called Array and each value is called an element. Each element occupies a numeric position in an array, known as its index.

 

Accessing the Elements of an Array

Array elements can be accessed by their index using the square bracket notation, and the index number is used to represent an element's position.

Array indexes are zero-based which means that the first item of an array isn’t stored at index 1, but 0. Hence, the second item is stored at index 1, and so on. Array indexes start at 0 and increase to the number of elements minus 1. In addition, an array of five elements would have indexes from 0 to 4.

The following example will show you how to get individual array elements by their index.

Example:

<html>
<head></head>
<body>
  <script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
document.write(fruits[0]); // Prints: Apple
document.write("<br>"+fruits[1]); // Prints: Banana
document.write("<br>"+fruits[2]); // Prints: Mango
document.write("<br>"+fruits[fruits.length - 1]); // Prints: Papaya
  </script>
</body>
</html>

Try with example

 

Note: In JavaScript, arrays are significantly a special type of object which has numeric indexes as keys. For arrays, the type of operator will return "object".

 

Getting the Length of an Array

The length of an array, which is the total number of elements contained in the array, is returned by the length property. Array length is constantly far greater than the index of any of its elements.

Example:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
document.write(fruits.length); // Prints: 5

Try with example
 

Looping Through Array Elements

In sequential order, the for-of loop can be used to access each element of an array, like this:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
// Iterates over array elements
for(var i = 0; i < fruits.length; i++) {    
    document.write(fruits[i] + "<br>"); // Print array element
}

Try with example

ECMAScript 6 which is a for-of loop has introduced a simpler way to iterate over array elements. To initialize and keep track of the loop counter variable in this loop isn’t mandatory (i).

Here's the same example is rewritten using the for-of loop:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
// Iterates over array elements
for(var fruit of fruits) {    
    document.write(fruit + "<br>"); // Print array element
}

Try with example

 

The for-in loop can be used to iterate over the array of elements, like this:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
// Loop through all the elements in the array 
for(var i in fruits) {  
    document.write(fruits[i] + "<br>");
}

Try with example

 

Note: Where the index order is important the for-in loop shouldn’t be used to iterate over an array. The for-in loop is optimized for iterating over an object's properties, hence, for loop with a numeric index or for-of loop should be used.

 

Adding New Elements to an Array

Simply use the push() method to add a new element at the end of an array, like this:

Example:

<html>
<head></head>
<body>
  <script>
  var colors = ["Red", "Green", "Blue"]; 
colors.push("Yellow");
 
document.write(colors); // Prints: Red,Green,Blue,Yellow
document.write(colors.length); // Prints: 4
  </script>
</body>
</html>

Try with example

Similarly, use the unshift() method to add a new element at the beginning of an array, like this:

Example:

var colors = ["Red", "Green", "Blue"]; 
colors.unshift("Yellow");
 
document.write(colors); // Prints: Yellow,Red,Green,Blue
document.write(colors.length); // Prints: 4

Try with example

 

You can also add multiple elements at once using the push() and unshift() methods, like this:

Example:

var colors = ["Red", "Green", "Blue"];
colors.push("Pink", "Voilet");
colors.unshift("Yellow", "Grey");
 
document.write(colors); // Prints: Yellow,Grey,Red,Green,Blue,Pink,Voilet
document.write(colors.length); // Prints: 7

Try with example


Removing Elements from an Array

The pop() method can be used to remove the last element from an array. This specific method returns the value that was popped out. Here's an example:

Example:

var colors = ["Red", "Green", "Blue"];
var last = colors.pop();
 
document.write(last); // Prints: Blue
document.write(colors.length); // Prints: 2

Try with example

 

Similarly, the first element can be removed from an array using the shift() method. This method returns the value that was shifted out as well. Here's an example:

var colors = ["Red", "Green", "Blue"];
var first = colors.shift();
 
document.write(first); // Prints: Red
document.write(colors.length); // Prints: 2

Try with example

 

Tip: “The push()” and “pop()” methods runs quite faster than “unshift()” and “shift()”. This is simply because the push() and pop() methods allow the addition and removal of elements at the end of an array causing the elements to remain in their initial position. On the other hand, unshift() and shift() methods allow the addition and removal of elements at the beginning of the array causing re-indexing of the whole array.

 

Adding or Removing Elements at Any Position

Being a very versatile array method, the splice() method allows addition or removal of elements from any index, using the syntax arr.splice(startIndex, deleteCount, elem1, …elemN).

This method takes three parameters and these parameters are as follows: 

  • The first parameter is required and it is the index at which to start splicing the array.
  • The second parameter is optional and it is the number of elements to remove. Zero (0) can be used to avoid removing any elements.
  • The third parameter is equally optional and it is a set of replacement elements.

 

The following example shows how it works:

Example:

var colors = ["Red", "Green", "Blue"];
var removed = colors.splice(0,1); // Remove the first element
 
document.write(colors); // Prints: Green,Blue
document.write(removed); // Prints: Red (one item array)
document.write(removed.length); // Prints: 1
 
removed = colors.splice(1, 0, "Pink", "Yellow"); // Insert two items at position one
document.write(colors); // Prints: Green,Pink,Yellow,Blue
document.write(removed); // Empty array
document.write(removed.length); // Prints: 0
 
removed = colors.splice(1, 1, "Purple", "Voilet"); // Insert two values, remove one
document.write(colors); //Prints: Green,Purple,Voilet,Yellow,Blue
document.write(removed); // Prints: Pink (one item array)
document.write(removed.length); // Prints: 1

Try with example

As seen from the above example, The splice() method returns an array of the deleted elements, or an empty array because no elements were deleted. In case the second argument, not the first argument is omitted, all elements from the start to the end of the array are removed. The splice() method modifies the array on which it is called on, unlike slice() and concat() methods.

 

Creating a String from an Array

Situations may arise where a string needs to be created by joining the elements of an array. The join() method can be used to do this. This method takes an optional parameter which is a separator string and is added in between each element. The JavaScript will use comma [,] by default if you omit the separator. The following example shows how it works:

Example:

<html>
<head></head>
<body>
  <script>
  var colors = ["Red", "Green", "Blue"];
 
  document.write(colors.join()); // Prints: Red,Green,Blue
  document.write("<br>");
  document.write(colors.join("")); // Prints: RedGreenBlue
  document.write("<br>");
  document.write(colors.join("-")); // Prints: Red-Green-Blue
  document.write("<br>");
  document.write(colors.join(", ")); // Prints: Red, Green, Blue
  </script>
</body>
</html>

Try with example

An array can also be converted to a comma-separated string using the toString(). This method unlike join() does not accept the separator parameter. Here's an example:

<html>
<head></head>
<body>
  <script>
  	var colors = ["Red", "Green", "Blue"];
	document.write(colors.toString()); // Prints: Red,Green,Blue
  </script>
</body>
</html>

Try with example


Extracting a Portion of an Array

Slice() method can be used to extract out a portion of an array or subarray without affecting the original array. This method takes 2 parameters and they are as follows:

  • Start index: This is the index at which to begin extraction.
  • An optional end index: This is the index before which to end extraction, like arr.slice(startIndex, endIndex).

Here's an example:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var subarr = fruits.slice(1, 3);
document.write(subarr); // Prints: Banana,Mango

Try with example

All elements to the end of the array are extracted if the endIndex parameter is omitted. In case negative indexes or offsets have been specified the slice() method can be used to extract the elements from the end of an array, rather than the beginning.

For example:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
document.write(fruits.slice(2)); // Prints: Mango,Orange,Papaya
document.write(fruits.slice(-2)); // Prints: Orange,Papaya
document.write(fruits.slice(2, -1)); // Prints: Mango,Orange

Try with example

 

Merging Two or More Arrays

To merge or combine two or more arrays the contact() method can be used. This method does not alter the existing arrays, rather it returns a new array.

For example:

var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"];
 
// Creating new array by combining pets and wilds arrays
var animals = pets.concat(wilds); 
document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra

Try with example

 

As shown in the example below, the contact() method can take any number of array arguments, so an array from any number of other arrays can be created.

var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"];
var bugs = ["Ant", "Bee"];
 
// Creating new array by combining pets, wilds and bugs arrays
var animals = pets.concat(wilds, bugs); 
document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra,Ant,Bee

Try with example

 

Searching Through an Array

Simply use the indexOf() and lastIndexOf() to search an array for a specific value. Both methods return an index representing the array element in case the value is found. Otherwise, -1 is returned if the value is not found. The indexOf() method and the lastIndexOf() returns the first one found and the last one found when used respectively.

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
document.write(fruits.indexOf("Apple")); // Prints: 0
document.write(fruits.indexOf("Banana")); // Prints: 1
document.write(fruits.indexOf("Pineapple")); // Prints: -1

Try with example

These two methods also accept an optional integer parameter from the index which specifies the index within the array at which to start the search.

Here's an example:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
// Searching forwards, starting at from- index
document.write(arr.indexOf(1, 2)); // Prints: 3
 
// Searching backwards, starting at from index
document.write(arr.lastIndexOf(1, 2)); // Prints: 0

Try with example

You can make of use the includes() method to find out whether certain elements are included in an array or not. Aside from the fact that this method returns true or false instead of an index number, it takes the same parameters as indexOf() and lastIndexOf() methods. 

For example:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
document.write(arr.includes(1)); // Prints: true
document.write(arr.includes(6)); // Prints: false
document.write(arr.includes(1, 2)); // Prints: true
document.write(arr.includes(3, 4)); // Prints: false

Try with example

 

The JavaScript find() method which is newly introduced in ES6 can be used to search an array based on certain conditions. The return of this method which is the value of the first element in the array satisfies the provided testing function. If not satisfied it returns undefined.

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
var result = arr.find(function(element) {
  return element > 4;
});
document.write(result); // Prints: 5

Try with example

 

One more significant method that is similar to find() is the findIndex() method which returns the index of a found element in the array instead of its value.

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
var result = arr.findIndex(function(element) {
  return element > 6;
});
document.write(result); // Prints: 8

Try with example

 

The find() method solely searches for the first element that satisfies the provided testing function. However, to find out all the matched elements use the filter() method because it creates a new array with all the elements that successfully pass the given test. 

The following example will show you how this actually works:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
var result = arr.filter(function(element) {
  return element > 4;
});
document.write(result); // Prints: 5,7
document.write(result.length); // Prints: 2

Try with example