Arrays in JavaScript

JavaScript Array is a collection of Multiple datatypes. inside a single variable. Arrays comes under Reference datatypes.

Arrays can store multiple data in a single variable. In Javascript, arrays can be collection of any datype. This means, an array can store both string, number or any other datatype together.

javascript arrays
Array in JavaScript


How to declare Array in JavaScript

Array in javascript can be declared using brackets[]. We can also use new Array() constructor function to declare Arrays. Both [] and new Array() works same. new Array() is constructor form, and brackets [] is literal form of Array.

JavaScript Array Literal

 
    var month=[];            // blank Array

JavaScript Array Constructor


    var month=new Array();        // blank Array
        

Check Array datatype

Arrays are Reference data types. typeof operator will return "object". To check datatype of a arrays, use Array.isArray() function. Array.isArray() function will determine whether the passed value is an Array or not.


var x=[];        
typeof x;            // return "object"
Array.isArray(x);    // return true                
        

Traversal values of array

To check element inside array, we can call array followed by index value in brackets. To find first element, call array[0]. This index notation starts from 0 to array.length-1.


var days=["sun","mon","tues"];
   
    days[0];        return "sun";  
    days[1];        return "mon";  
    days[2];        return "tues";  
    days[3];        return undefined;  
       

array.length

array.length property is used to check total numbers of elements inside array. Default length is zero, for an empty array. For a non empty Array, array.length is positive number.

    var x=[];
    var y=["jan","feb","mar"];
    
    x.length;        return 0;                  
    y.length;        return 3;                  
        

In JavaScript, Array length is mutable. This means, we can manually change length of an array. If default length is 3, and we assign array.length=5, new length of array will be 5 with two undefined.


var days=["sun","mon","tues"];
days.length;   //return 3
    
days.length=5;
days.length;   //return 5
       
days           //return ["sun","mon","tues",,] 2 empty
       
days.length=6;
days.length;   //return 6
       
days           //return ["sun","mon","tues",,,] 3 empty                            
        

Array Methods

In JavaScript, Arrays are used to store multiple data inside single variable. Arrays have properties are methods. Array.length is Array property. Now we will discuss array methods.


sort()

array.sort() will sort the order an array. This will change Alphabetical order or an array. array.sort() will also change order of an array permanently.


var days=["sun","mon","tues","wed","thurs","fri","sat"];

days.sort();
days 
// return ["fri", "mon", "sat", "sun", "thurs", "tues", "wed"]    

sort method will also sort numeric array in alphabetical order.


    var i=[1,2,3,10,20];    
    i.sort();
    i;  return [1,10,2,20,3];

Sort numeric array

To sort numeric array, pass a callback function in sort method.


    var i=[1,2,3,10,20];
    function srt(a,b){ retrun a-b }    
    i.sort(srt);
    i;  return [1,2,3,10,20];

reverse()

array.reverse() method is used to reverse an array. this will bring last element to first and first element to last.


var days=["sun","mon","tues","wed","thurs","fri","sat"];
days.reverse();
days;
    // ["sat", "fri", "thurs", "wed", "tues", "mon", "sun"]

indexOf()

array.indexOf() method is used to check index of first element in array.


var days=["sun","mon","tues","wed","thurs","fri","sat"];

days.indexOf("sun");         // return 0
days.indexOf("sat");         // return 6
days.indexOf("SUN");         // return -1

use array.lastIndexOf() to check last index of an element in array.


shift

array.shift() method is used to remove first element from an array. This will reduce array length by 1 as first element is removed.


var days=["sun","mon","tues"];

days.shift();        // return "sun"
days;               //return ["mon","tues"] 

unshift

array.unshift() method is used to add first element in an array. This will increase array length by 1 as one element is added on zero index.


var days=["sun","mon","tues"];

days.unshift("DAYS");     // return 4
days;                     //return ["DAYS","sun","mon","tues"] 

pop

array.pop() method is used to remove last element from an array. This will also decrease array length by 1 as last element is removed .


var days=["sun","mon","tues"];

days.pop();     // return "tues"
days;                     //return ["sun","mon"] 

push

array.push() method is used to add an element in array ar last position. This will also increase array length by 1 as one element is added.


var days=["sun","mon","tues"];

days.push("wed");     // return 4
days;                     //return ["sun","mon","tues","wed"] 

splice

array.splice() method is used to add or remove n number of elements from an array at any position. This will also increase or decrease array length by n as n elements are added or removed.


var days=["sun","mon","tues"];

days.splice(0,1);  // remove 1 element from 0 index
days               // return  ["mon","tues"];

days.splice(1,1);  // remove 1 element from 1 index
days               // return  ["sun","tues"];

days.splice(0,2);  // remove 2 element from 0 index
days               // return  ["tues"];

days.splice(0,0,"days"); // add 1 element at 0 index
days                     // return  ["days","sun","mon","tues"];

days.splice(0,1,"days"); // add 1 element by removing element at 0 index
days                     // return  ["days","mon","tues"];


pop, push, shift, unshift and splice methods can manipulate array data.


slice

array.slice() method is used to slice a single element from array. This will not change actual array. slice can return single element if parameter passed is single. For two parameter(x,y), slice can return y-x elements.


var days=["sun","mon","tues"];

days.slice(0);        return ["sun","mon","tues"];
days.slice(1);        return [mon","tues"];
days.slice(2);        return ["tues"];
days.slice(1,3);      return ["mon","tues"];

join

array.join() method is used to convert an array to string with all elements inside array, separated by commas. To change default separator from commas to any other character by passing that inside parenthesis.


var days=["sun","mon","tues"];

days.join();        return "sun,mon,tues";
days.join(":");     return "sun:mon:tues";
days.join("-");     return "sun-mon-tues";


concat

array.concat() method is used to merge or concat an array to another array. After join, we will get a new array.


var days1=["sun","mon","tues"];
var days2=["wed","thurs","fri","sat"];

var days=days1.concat(days2);

days;  // return ["sun","mon","tues","wed","thurs","fri","sat"]


split, string to array

split is used to convert a string to array.


var str="abc,efg";
   
    str=str.split("");      
                    // return ["a","b","c",",","e","f","g"]
                    
    str=str.split(",");
                   // return ["abc","efg"]

Multidimensional Array

Multidimensional Array means an Array inside another array or an array of arrays. We can store n numbers of arrays inside array.


    var students=[["g1","g2","g3"],["b1","b2","b3","b4"]];
    
    students.length;               // 2 arrays in array
    students[0];                   // first array in students
    students[1];                   // second array in students
    stuents[0].length              // 3
    stuents[1].length              // 4
    students[0][0];                // "g1"
    students[0][1];                // "g2"
    students[0][2];                // "g3"
    students[1][0];                // "b1"
    students[1][1];                // "b2"
    students[1][2];                // "b3"
    students[1][3];                // "b4"