jQuery Arrays

In this tutorial, we will try to understand arrays in jQuery, in other words how they are handled, how values are stored and how they are implemented.

Arrays are zero indexed, ordered lists of values. They are really handy for storing a set of values of the same data type.

Let's start with how to create an Array in jQuery:

Code 1:

var names = new Array(“Name1”,”Name2”);

Code 2:

var names = [“Name1”,”Name2”] //Recommended

Both of the preceding approaches are kind of static declarations. Now let's do some dynamic programming with Arrays..
 

var namearray = [];

namearray.push(“Name1”) //Index 0

namearray.push(“Name2”) //Index 1

namearray.push(“Name3”) //Index 2

Here, .push() is a jQuery function used in conjunction with Arrays that add an element at the end of the array. Items can be inserted by specifying the index as well, as follows:

namearray[0] = “Name1”;
namearray[1] = “Name2”;
namearray[2] = “Name3”;

Now let’s print the values of the array:

Console.log(namearray);

The statement above will produce the output as [ "Name1", "Name2",”Name3”].

We can see that we just printed the array object but not the individual values, so to extract individual values the following statement can be executed:

Console.log(namearray[0]) //Name1;
Console.log(namearray[1]) //Name2;

How to print an array of values using a for loop in jQuery:
 

var myArray = ["Name1", "Name2", "Name3"];

for (var i = 0; i < myArray.length; i = i + 1) {

    console.log(myArray[i]);

}

How to print an array of values using $.each() in jQuery:
 

$.each(myArray, function (index, value) {

          console.log(index + ": " + value);

      });

Commonly used Array Methods and Properties in jQuery

1. length = This property is used to determine the number of items available in the array.

console.log(myArray.length); //3

2. concat() = This method is used to concat two arrays.
 

var firstArray = [2, 3, 4];

var secondArray = [5, 6, 7];

var concatArray = firstArray.concat(secondArray); // [ 2, 3, 4, 5, 6, 7 ]

3. pop() = This method removes the last element from the specified array.
 

var numberArray = [];

numberArray.push(0); // [ 0 ]

numberArray.push(2); // [ 0 , 2 ]

numberArray.push(7); // [ 0 , 2 , 7 ]

numberArray.pop(); // [ 0 , 2 ]

4. slice() = This method is used to extract a part from the array.
 

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8];

var newArray = numberArray.slice(3);

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

console.log(newArray); // [ 4, 5, 6, 7, 8 ]