JS Arrays

What is an Array

Arrays are complex variables that enable us to keep multiple values or a collection of values using a single variable name. JavaScript arrays can hold any valid data type, including strings, numbers, objects, functions, and even other arrays, which allows for the creation of more intricate data structures like arrays of objects or arrays of arrays.

Imagine you want to save a list of color names in your JavaScript code. Storing each color name individually in a variable would look like this:

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

But what if you need to store the names of states or cities in a country, and this time there are not just three, but maybe hundreds. It would be quite tedious and boring to store each one in a separate variable. Moreover, using so many variables at once and keeping track of them all would be very difficult. This is where arrays come in handy. Arrays solve this problem by providing an organized structure to store multiple values or a collection of values.

Creating an Array

The easiest way to create an array in JavaScript is by enclosing a comma-separated list of values within square brackets ([]), as shown in the following syntax:

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

Arrays can also be created using the Array() constructor, as shown in the following syntax. However, for simplicity, the previous syntax is recommended.

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

Here are some examples of arrays created using the 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 array is an organized collection of values. Each value in an array is called an element, and each element has a numeric position in the array, known as its index.


Accessing the Elements of an Array

Array elements can be accessed by their index using square bracket notation. An index is a number that indicates an element's position in an array.

Array indexes are zero-based. This means the first item in an array is at index 0, not 1. The second item is at index 1, and so on. Array indexes start at 0 and go up to the number of elements minus 1. So, an array with five elements would have indexes from 0 to 4.

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

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

document.write(fruits[0]); // Prints: Apple
document.write(fruits[1]); // Prints: Banana
document.write(fruits[2]); // Prints: Mango
document.write(fruits[fruits.length - 1]); // Prints: Papaya

 

Note: In JavaScript, arrays are actually a special type of object with numeric indexes as keys. The typeof operator will return "object" for arrays.


Getting the Length of an Array

The length property returns the number of elements in an array. The array length is always greater than the index of its last element.

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

Looping Through Array Elements

You can use a for loop to access each element of an array in order, 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
}

ECMAScript 6 introduced a simpler way to iterate over array elements, which is the for-of loop. In this loop, you don't need to initialize or keep track of the loop counter variable (i).

Here's the same example 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
}

You can also iterate over the array elements using the for-in loop, 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>");
}

Note: The for-in loop should not be used to iterate over an array where the index order is important. This loop is optimized for iterating over object properties. It's better to use a for loop with a numeric index or for-of loop for arrays.


Adding New Elements to an Array

To add a new element at the end of an array, you can use the push() method, like this:

var colors = ["Red", "Green", "Blue"]; 
colors.push("Yellow");

document.write(colors); // Prints: Red,Green,Blue,Yellow
document.write(colors.length); // Prints: 4

To add a new element to the start of an array, you can use the unshift() method, like this:

var colors = ["Red", "Green", "Blue"]; 
colors.unshift("Yellow");

document.write(colors); // Prints: Yellow,Red,Green,Blue
document.write(colors.length); // Prints: 4

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

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

Removing Elements from an Array

To remove the last element from an array, you can use the pop() method. This method returns the value that was removed. Here's an example:

var colors = ["Red", "Green", "Blue"];
var last = colors.pop();

document.write(last); // Prints: Blue
document.write(colors.length); // Prints: 2

Similarly, you can eliminate the first element from an array with the shift() method. This action also gives back the value that was shifted out. Here's an illustration:

var colors = ["Red", "Green", "Blue"];
var first = colors.shift();

document.write(first); // Prints: Red
document.write(colors.length); // Prints: 2

Tip: The push() and pop() methods are faster than unshift() and shift(). This is because push() and pop() simply add and remove elements at the end of an array without moving other elements, whereas unshift() and shift() add and remove elements at the beginning of the array, requiring re-indexing of the entire array.


Adding or Removing Elements at Any Position

The splice() method is a versatile array method that allows you to add or remove elements from any index using the syntax arr.splice(startIndex, deleteCount, elem1, ..., elemN).

This method takes three parameters: the first parameter is the index at which to start splicing the array (required), the second parameter is the number of elements to remove (use 0 if you don't want to remove any elements), which is optional, and the third parameter is a set of replacement elements, also optional. The following example demonstrates how it works:

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

The splice() method returns an array of the deleted elements, or an empty array if no elements were deleted, as demonstrated in the above example. If the second argument is omitted, all elements from the start to the end of the array are removed. Unlike the slice() and concat() methods, the splice() method modifies the array it is called on.


Creating a String from an Array

Sometimes, you may simply want to create a string by joining the elements of an array. You can achieve this using the join() method. This method takes an optional parameter, which is a separator string added between each element. If you omit the separator, JavaScript will use a comma (,) by default. The following example illustrates how it works:

var colors = ["Red", "Green", "Blue"];

document.write(colors.join()); // Prints: Red,Green,Blue
document.write(colors.join("")); // Prints: RedGreenBlue
document.write(colors.join("-")); // Prints: Red-Green-Blue
document.write(colors.join(", ")); // Prints: Red, Green, Blue

You can also convert an array into a string separated by commas using the toString() method. Unlike join(), this method doesn't allow specifying a separator. Here's an example:

var colors = ["Red", "Green", "Blue"];
document.write(colors.toString()); // Prints: Red,Green,Blue

Extracting a Portion of an Array

If you wish to extract a portion of an array (i.e., a subarray) while preserving the original array, you can utilize the slice() method. This method requires two parameters: the start index (the index from which extraction begins) and an optional end index (the index before which extraction ends), specified as 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

If you don't include the endIndex parameter, all elements until the end of the array are extracted. You can also use negative indexes or offsets — in these cases, the slice() method extracts elements from the end of the array instead of the beginning. For instance:

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

Combining Two or More Arrays

The concat() method allows you to merge or join two or more arrays. It doesn't alter the original arrays; instead, it creates a new array. For instance:

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

The concat() method can accept any number of array arguments, enabling you to form an array from multiple other arrays, as demonstrated in the following example:

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

Searching Through an Array

If you need to find a specific value in an array, you can use the indexOf() and lastIndexOf() methods. When the value is found, both methods return an index representing the array element. If the value isn't found, -1 is returned. The indexOf() method returns the index of the first occurrence, while lastIndexOf() returns the index of the last occurrence.

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

Both methods also take an optional integer parameter called from index, which indicates the index within the array to begin the search from. 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

You can also utilize the includes() method to determine if an array contains a specific element. This method accepts the same parameters as the indexOf() and lastIndexOf() methods, but it returns true or false instead of an index number. 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

If you need to search an array based on a specific condition, you can utilize the JavaScript find() method, which was introduced in ES6. This method returns the value of the first element in the array that meets the criteria specified by the provided testing function. Otherwise, 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

Another method similar to find() is findIndex(), which returns the index of a found element in the array instead of its value. For example:

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

The find() method only searches for the first element that meets the specified testing function. If you want to find all matched elements, you can utilize the filter() method.

The filter() method generates a new array containing all elements that pass the specified test. The following example demonstrates how this 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