Arrays in JavaScript

Arrays

The array object allows you to store multiple values in one variable. It stores data in sequence form having same type. JavaScript arrays can store any valid value, including strings, numbers, objects, functions, and even other arrays, thus making it possible to create more complex data structures such as an array of objects or an array of arrays.

Creating an array

You can create an array in JavaScript by creating a list of elements separated by comma and enclosed in square brackets [].

var firstArray=[element0, element1, element2……element];

Let us take some examples of arrays:

var colorName=[“red”, “green”, “purple”];
var fruitsName=[“banana”, “apple”, “orange”];

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

In above example, the elements can be accessed as follows:

firstArray[0]=”red”;

firstArray[1]=”green”;

firstArray[2]=”purple”;

Accessing array elements in JavaScript

The elements in an array can be accessed by using their index with square bracket notation. An index is a number that represents the position of an element in an array. The index value starts with 0 and increases by an increment by one. The first position will be [0], second will be at [1], the third position will be [2] and so on. So, array of six elements would have indexes from 0 to 5.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arrays in JS</title>
</head>
<body>
    <script>
        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
    </script>
</body>
</html>

It will result as AppleBananaMango

How to get the length of Array in JavaScript?

When you have created an array in JavaScript, you may need to know the length of that array i.e. you may require the number of elements contained in the array. You can find the number of elements of array by using the length property of array. Array length is always greater than the index of any of its elements. Let us take an example of an array to find its length.

var vegetable=["Carrot", "Cauliflower", "Cabbage"];
document.write(vegetable.length);

It will give the length of array vegetable as 3.

Looping of array elements

When you need to access each element of an array, you can do that with the help of for loop. There are four types of for loop in JavaScript which can be used in your code.

  • for loop using length property of an array
  • for-of loop
  • for-in loop
  • forEach()

Let us take an example of for loops

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Looping in JS</title>
</head>

<body>
    <h3>For loop using length property</h3>
    <script>
        var fruits = ["Orange", "Mango", "Papaya", "Grapes"];
        // Iterates over array elements
        for (var i = 0; i < fruits.length; i++) {
            document.write(fruits[i] + "<br>"); // Print array element
        }
    </script>
    <h3>For-of loop</h3>
    <script>
        var vegetables = ["Potato", "Carrot", "Brocolli"];
        for (var veg of vegetables) {
            document.write(veg + "</br>");
        }
    </script>
    <h3>For-in loop</h3>
    <script>
        var vegetables2 = ["Cauliflower", "Tomato", "Raddish"];
        for (var i in vegetables2) {
            document.write(vegetables2[i] + "</br>");
        }
    </script>
</body>
</html>

It result as shown below:

array in javascript, www.programmingtutorial.in

How to add new element to an array?

You can add a new element to an existing array at the end of an array by using push() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Looping in JS</title>
</head>
<body>
    <h3>Adding an element to an array</h3>
    <script>
        var fruits = ["Orange", "Mango", "Papaya", "Grapes"];
        document.write(fruits +"</br>");
        fruits.push("Banana");
        document.write(fruits);
    </script>  
</html>

Adding an element to an array

Orange,Mango,Papaya,Grapes
Orange,Mango,Papaya,Grapes,Banana

How to remove last element of an array?

You can add a new element to an array, but what about removing an element? The last element of an array can be easily removed by using pop() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arrays in JS</title>
</head>
<body>
    <h3>Removing an element from an array</h3>
    <script>
        var fruits = ["Orange", "Mango", "Papaya", "Grapes"];
        document.write(fruits +"</br>");
        document.write("The removed element is given below </br>");
        var del=fruits.pop();
        document.write(del +"</br>");  // Will print Grapes
        document.write("The remaining array list after removal of last element </br>");
        document.write(fruits);
    </script>  
</html>

It results as

Removing an element from an array

Orange,Mango,Papaya,Grapes
The removed element is given below
Grapes
The remaining array list after removal of last element
Orange,Mango,Papaya

How to add or remove an element at any position of an array?

Just like an element is added or removed at last position by using push() and pop() method, an element can also be added or removed at any position of an array. This can be achieved by using splice() method of an array. Its syntax is:

arrayName.splice(startingIndex, deleteCount, Elem1, Elem2,…..ElemN);

The method takes three parameters, the index from where the splicing of an array will occur, second is the deleteCount which specifies how many elements will be removed and the third parameter used to add elements. If you don’t want to delete an element then keep deleteCount as 0. The splice() method modifies an array. Let us take some examples:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arrays in JS</title>
</head>

<body>
    <h3>Removing and inserting element from/in an array</h3>
    <script>
        var fruits = ["Orange", "Mango", "Papaya", "Grapes"];
        var removed=fruits.splice(0, 1);
        document.write(removed +"</br>");  //Will remove an element at index 0 which is orange

        var insert=fruits.splice(1, 0, "Banana", "Kiwi"); //Will insert two elements at index 1 without deleting
        document.write(fruits +"</br>");

        var del=fruits.splice(2, 2, "Pears"); //Will delete an elemet at index 2 and insert Pears
        document.write(fruits +"</br>");
    </script>  
</html>

The result of above code is

Removing and inserting element from/in an array

Orange
Mango,Banana,Kiwi,Papaya,Grapes
Mango,Banana,Pears,Grapes

How to extract a portion of an array?

An array can be extracted in JavaScript by keeping original array intact with the help of slice() method. In other words, you can say the slice() method creates a subarray. Its syntax is:

array.slice(startingIndex, endingIndex)

This method takes two parameters as startingIndex at which extraction will be started and an optional endingIndex before which the extraction will be stopped. If endingIndex has not been given, it will extract all the element falling after the startingIndex. Let us take an example to better understand the concept.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arrays in JS</title>
</head>
<body>
    <h3>Extracting elements from an array</h3>
    <script>
        var fruits = ["Orange", "Mango", "Papaya", "Grapes"];
        var subArray=fruits.slice(1, 3);
        document.write(subArray +"</br>");  //Will extract Mango, Papaya
        var subArr=fruits.slice(1);
        document.write(subArr);
    </script>  
</html>

Extracting elements from an array

Mango,Papaya
Mango,Papaya,Grapes

How to merge two arrays in JavaScript?

If you have two arrays in JavaScript and you want to combine them as one, you can do that with the help of concat() method of JavaScript. This method does not alter an existing array instead it creates a new array by combining two or more individual arrays. Let us write a code for concatenating arrays.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arrays in JS</title>
</head>
<body>
    <h3>Arrays concatenation</h3>
    <script>
        var winterFruits = ["Orange", "Apple", "Kinnu"];
        var summerFruits=["Watermelon", "Melon", "Grapes", "Pears"];
        var dryFruits=["Almonds", "Walnuts", "Cashews"];
        var fruits=winterFruits.concat(summerFruits);
        document.write(fruits +"</br>");
        
        var combFruits=winterFruits.concat(summerFruits, dryFruits);
        document.write(combFruits +"</br>");
    </script>  
</html>

Arrays concatenation

Orange,Apple,Kinnu,Watermelon,Melon,Grapes,Pears
Orange,Apple,Kinnu,Watermelon,Melon,Grapes,Pears,Almonds,Walnuts,Cashews