JavaScript Arrays

Array in javascript is combination of order elements. Each element of array, are retrieved by integer index value. Array elements can be combination of similar and different object.

Declaration of Array

There is two ways to create an array in Javascript. They syntactically different but provide similar functionality.

var arrayFirst = new Array();
var arraySecond = [];

In this both statement creating an empty array. And arrayFirst and arraySecond variables is store the reference of that array.

Create Empty Array in Javascript

We can also create an array of initial values. Array elements are define within the square brackets [] and each elements are separated by comma (,).

//Array which are contain integer values
var arr1 = [1,2,3,4]
//Array which is containing string elements
var arr2 = ["C","C++","Java","Kotlin","Ruby"]

//Array that is containing combination of different element
var arr3 = [1,"One",1.0,true,false,'1']

console.log(arr1);
console.log(arr2);
console.log(arr3);
Array example in JavaScript
[ 1, 2, 3, 4 ]
[ 'C', 'C++', 'Java', 'Kotlin', 'Ruby' ]
[ 1, 'One', 1, true, false, '1' ]

When retrieve particular element of array then using of index value. Note that first index element of array are start to zero and total elements of array are represented its size.

//Array which are contain integer values
var arr1 = [1,2,3,4]
//Array which is containing string elements
var arr2 = ["C","C++","Java","Kotlin","Ruby"]

//Array that is containing combination of different element
var arr3 = [1,"One",1.0,true,false,'1']

console.log(arr1[2]); //3
console.log(arr2[4]); //Ruby
console.log(arr3[3]); //1.0
3
Ruby
true

Array Methods

Method Overview
array.push(...elements) Added single or multiple elements at the end
array.pop() Remove last element of arrays, and returning that value
array.shift() Remove first element of arrays, and returning that value
array.concat(arr1,arr2,..) Combining of two or more array elements and returning this new array
array.copyWithin() Copies specified array elements within the array
array.fill(element) fill (set) a new element value to every element of array
array.filter() This method are create new array under the course condition
array.indexOf(value) Finding the array element by value, and returns its index.
Array.isArray(array) Check given object is an array or not if array then returns true, otherwise returns false value.
array.join() combines of all array element into a string
array.includes(element) Check If an array is contains specific value element
array.reverse() reverse the order of an array elements
array.toString() Converting array element into an string and return that result
array.unshift() Adds a single or multiple elements at the Beginning
array.from() Creates an array from an using an object

array.push()

push() method are used to add new element into the end of array. This method are accept one parameter value, This value can be form of a single element, an array and variable length argument. When that is form of multiple element then that are separated by (,) comma.

//Create Array of 4 elements
var arr = [1,2,3];
console.log("First Test : ",arr);

//Add a single element 
arr.push(4); 
console.log("Second Test : ",arr);

//Add multiple element into end
arr.push(5,6); //Add Two element in this case
console.log("Third Test : ",arr);

//Add an array to end of array
arr.push([7,8,9]);
console.log("Fourth Test : ",arr);
Array push method example
First Test :  [ 1, 2, 3 ]
Second Test :  [ 1, 2, 3, 4 ]
Third Test :  [ 1, 2, 3, 4, 5, 6 ]
Fourth Test :  [ 1, 2, 3, 4, 5, 6, [ 7, 8, 9 ] ]

array.unshift()

unshift() method are used to add new element into the beginning of array.

//Create Array of 4 elements
var arr = [1,2,3];
console.log("First Test : ",arr);

//Add a single element 
arr.unshift(4); 
console.log("Second Test : ",arr);

//Add multiple element into Beginning
arr.unshift(5,6); //Add Two element in this case
console.log("Third Test : ",arr);

//Add an array to Beginning of array
arr.unshift([7,8,9]);
console.log("Fourth Test : ",arr);
First Test :  [ 1, 2, 3 ]
Second Test :  [ 4, 1, 2, 3 ]
Third Test :  [ 5, 6, 4, 1, 2, 3 ]
Fourth Test :  [ [ 7, 8, 9 ], 5, 6, 4, 1, 2, 3 ]

array.pop()

pop() method are remove one element into last of array and this method are return this deleted element. In case array are no element then this method is returning a undefined.

//Create Array of 4 elements
var arr = [1,[1,2,3],4];
console.log("Array : ",arr);

//Remove last element of arr
var element = arr.pop();
console.log("Remove Element : ",element);
console.log("Array : ",arr);

//Remove last element of arr
element = arr.pop();
console.log("Remove Element : ",element);
console.log("Array : ",arr);

//Remove last element of arr
element = arr.pop();
console.log("Remove Element : ",element);
console.log("Array : ",arr);


//Last case when array is empty
element = arr.pop();
console.log("Remove Element : ",element);
console.log("Array : ",arr);
Array :  [ 1, [ 1, 2, 3 ], 4 ]
Remove Element :  4
Array :  [ 1, [ 1, 2, 3 ] ]
Remove Element :  [ 1, 2, 3 ]
Array :  [ 1 ]
Remove Element :  1
Array :  []
Remove Element :  undefined
Array :  []

array.shift()

shift() method are remove one element into beginning of array and this method are return this deleted element. In case array are no element then this method is returning a undefined. That is reversal version of pop() method

//Create Array of 4 elements
var arr = [1,[1,2,3],4];
console.log("Array : ",arr);

//Remove first element of arr
var element = arr.shift();
console.log("Remove Element : ",element);
console.log("Array : ",arr);

//Remove first element of arr
element = arr.shift();
console.log("Remove Element : ",element);
console.log("Array : ",arr);

//Remove first element of arr
element = arr.shift();
console.log("Remove Element : ",element);
console.log("Array : ",arr);


//first case when array is empty
element = arr.shift();
console.log("Remove Element : ",element);
console.log("Array : ",arr);
Array :  [ 1, [ 1, 2, 3 ], 4 ]
Remove Element :  1
Array :  [ [ 1, 2, 3 ], 4 ]
Remove Element :  [ 1, 2, 3 ]
Array :  [ 4 ]
Remove Element :  4
Array :  []
Remove Element :  undefined
Array :  []

array.concat()

This method are used to combine two or more arrays.

array1.concat(arr2,arr3,...)
//Create Arrays
var arr1 = [1,2,3];
var arr2 = [true,false];
var arr3 = ["J","S"];
var arr4 = [1.15,2.30];

var test1 =arr1.concat(arr3); //concat arr1+arr3
console.log(test1);

var test2 =arr2.concat(arr3,arr4); //concat arr2+arr3+arr4
console.log(test2);
concat an array elements in JavaScript
[ 1, 2, 3, 'J', 'S' ]
[ true, false, 'J', 'S', 1.15, 2.3 ]

array.copyWithin()

array.copyWithin(targetIndex, startIndex, endIndex)
var array =[0,1,2,3,4,5,6,7];
array.copyWithin(3,0,7);
console.log(array);
[ 0, 1, 2, 0, 1, 2, 3, 4 ]

array.fill()

var array =[0,1,2,3,4,5,6,7];
array.fill(0);
console.log(array);
[ 0, 0, 0, 0, 0, 0, 0, 0 ]

array.filter()

function oddValue(el){
  if((el%2)!=0){
    return el;
  }
}
var array =[1,2,3,4,5,6,7];
var evenElement=array.filter(function(e){ if(e%2==0){ return e}});
var oddElement=array.filter(oddValue);

console.log(array);
console.log(evenElement);
console.log(oddElement);
[ 1, 2, 3, 4, 5, 6, 7 ]
[ 2, 4, 6 ]
[ 1, 3, 5, 7 ]

array.indexOf()

This method are return an element of given index in case given element are not valid then this method is returning the value of -1.

var array =[1,2,3,4,5];

console.log(array.indexOf(1));
console.log(array.indexOf("one"));
0
-1

Array.isArray(array)

This method are returning the true value when given argument is an array. otherwise this method are returning a false value.

function testArray(parms){
  //method which is check array element
  if(Array.isArray(parms)){
    console.log("That is an array");
  }else{
    console.log("Not array");
  }
}

var array =[1,2,3,4,5];

testArray(array);
testArray(123);
testArray([1,2,4]);
That is an array
Not array
That is an array

array.join()

combines of all array element into a string.

var array = [1,2,true,3,4,"hello"];
var text =array.join(" ");//Separated by space charchar
console.log(array);
console.log(text);
[ 1, 2, true, 3, 4, 'hello' ]
1 2 true 3 4 hello

array.includes(element)

This method are check array element are exist or not exist. if element is exist then this method are returning the true value otherwise returning the false value.

var array =[1,2,3,4,5];

console.log(array.includes(1));
console.log(array.includes("one"));
console.log(array.includes(3));
console.log(array.includes(33));
true
false
true
false

array.reverse()

This method are reversed an existing array.

var array =[1,2,3,4,5];

console.log("Before ",array);
//Reverse array element
array.reverse();

console.log("After ",array);
Before  [ 1, 2, 3, 4, 5 ]
After  [ 5, 4, 3, 2, 1 ]

array.toString()

var array =[1,2,3,4,5];
var text=array.toString()
console.log(array);
console.log(text);
[ 1, 2, 3, 4, 5 ]
1,2,3,4,5

array.from()

var array = Array.from("JAJA SCRIPT")
console.log(array);
[ 'J', 'A', 'J', 'A', ' ', 'S', 'C', 'R', 'I', 'P', 'T' ]

Useful Operation In Arrays

In this section are including basic example and inbuilt method which are provide easierity to use arrays.

Referencing of arrays

Array variable are holds reference of array. When assigning of this variable into another variable. Then In this situation both variables reference the same array. When anyone variable are modified this array element such as perform operation of update, delete and add. That changes are automatic applied to second variable. Because both are share same array by reference. Let see one example.

//Define array of integer value
var firstArray=[1,2,3,4];
//Assign First array reference to second array
var secondArray=firstArray;

//Before Array Element
console.log("Before Array ");
console.log("First Array : ",firstArray);
console.log("Second Array : ",secondArray);

//When modified second array
secondArray[0]="one";
secondArray[1]="two";

//After update array elements
console.log("\nAfter Array ");
console.log("First Array : ",firstArray);
console.log("Second Array : ",secondArray);
Referencing of array elements
Before Array 
First Array :  [ 1, 2, 3, 4 ]
Second Array :  [ 1, 2, 3, 4 ]

After Array 
First Array :  [ 'one', 'two', 3, 4 ]
Second Array :  [ 'one', 'two', 3, 4 ]

Copy of Array Elements

slice() method are used to copy array elements and this method are return a new array.

//Define array of integer value
var firstArray=[1,2,3,4];
//In this case copy array element
var secondArray=firstArray.slice();

//Before Array Element
console.log("Before Array ");
console.log("First Array : ",firstArray);
console.log("Second Array : ",secondArray);

//When modified second array
secondArray[0]="one";
secondArray[1]="two";

//After update array elements
console.log("\nAfter Array ");
console.log("First Array : ",firstArray);
console.log("Second Array : ",secondArray);
Copy an Array Elements
Before Array 
First Array :  [ 1, 2, 3, 4 ]
Second Array :  [ 1, 2, 3, 4 ]

After Array 
First Array :  [ 1, 2, 3, 4 ]
Second Array :  [ 'one', 'two', 3, 4 ]

Flatten all Nested Array element

//flatten all multidimensional nested array
function flatArray(oldarray,newArray){
  
  //iterate array element
  for(var i in oldarray){

    if(Array.isArray(oldarray[i])){
      //When  element is an array 
      //Recursive execute this function and simplify
      flatArray(oldarray[i],newArray);
    }else{
      //When array element is not an array
      //Then added this element into new array
      newArray.push(oldarray[i]);
    }
  }
}


//Nested multidimensional array
var oldarray = [1,2,3,[4,5,6,[7,8,[9,[10,11,[12,15,[16]]]]]]];

//Make an empty Array
var newArray=[];

//This method are 
flatArray(oldarray,newArray);

console.log(newArray);
Flatten all Nested Array element
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 16 ]

Nested array Initialization

Nested array or nested structure are used to simplify the complex structure of data arrangement.

//Create nested array
var arrayElements=["First","Second",[1,2,3],true,false,[1.2,1.4]]
console.log(arrayElements)
Nested array Initialization In Javascript
[ 'First', 'Second', [ 1, 2, 3 ], true, false, [ 1.2, 1.4 ] ]

Get the element of nested array is similar to get simple array [] are separates their dimension.

//Create nested array
var arrayElements=["First","Second",[1,2,3],true,false,[1.2,1.4]];
console.log(arrayElements[0]);
console.log(arrayElements[2][0]);
console.log(arrayElements[5][1]);
First
1
1.4


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved