Know About JavaScript Array

Arrays In JavaScript

An array is a collection and it is zero-indexed.  The meaning of this is the first element is at index zero and the last element is at index of array length -1 position.

The array in JavaScript has length property which returns the size of that array.

Example:

var array = [];
console.log("Array Length -- "+ array.length);
JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

var array = new Array(100);
console.log("Array Length -- "+ array.length);

In this example we only initialize the array and we are not adding any element in array. If you see the output you will see we initialize at 100 and length is also 100.

JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

How to retrieve first and last element in array?

var array = [100,200,300]
console.log("First Element -- " +array[0]);
console.log("Last Element -- " + array[array.length-1]);

document.write("Array Is " + array+"<br/>");

document.write("First Element -- " + array[0] + "<br/>");
document.write("Last Element -- " + array[array.length - 1] + "<br/>");
JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

Different ways to declare Array in JavaScript

  1. Declaring and populating array at the same time
Var array=[10,20,30];
Console.log(array);

Declaring array with array constructor: in this method we declare array with array constructor and then populate this array with the index. In JavaScript the array are not fixed length array type in other languages like c#,java this will grow dynamically even though they will declared with fixed length.

var constructor_array = new Array(2);
constructor_array[0] = 10;
constructor_array[1] = 20;
constructor_array[3] = 30;
console.log(constructor_array);
console.log("Second Array Length - "+constructor_array.length);
JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

Push and Pop methods of JavaScript Array:

There are 2 methods to add element in array below is basic method where we can assign value to array index variable.

document.writeln("<br/>");
for (var i = 0; i < 10; i++) {
    var val = (i + 1) * 2;
    myarray[i] = val;    
}

In this code, we adding values from 0 to 9 index and always point to remember the array index start with 0.

To print these elements in array again we use an array with index to print like below.

for (var i = 0; i < 10; i++) {
    document.writeln(myarray[i]);
    document.writeln("<br/>");
}

Below Is complete code to add elements in array and display on a page

var myarray = [];
document.writeln("<H4> Showing Elements In Array Regular way</H4>");

document.writeln("<br/>");
for (var i = 0; i < 10; i++) {
    var val = (i + 1) * 2;
    myarray[i] = val;
    document.writeln('myarray[' + i + '] =' + val);
    document.writeln("<br/>");
}

document.writeln("<H4> Showing Elements In Array</H4>");
document.writeln("<br/>");

for (var i = 0; i < 10; i++) {
    document.writeln(myarray[i]);
    document.writeln("<br/>");
}

The output of code like below

JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

Now we will see the push and pop method using the same strategy

Push Method:

 This method adds a new item to the end of array and using this length of the array is changed.

for (var i = 0; i < 10; i++) {
    var val = (i + 1) * 2;
    myarray.push(val);    
}

Pop Method:

It will remove the last element of an array and also this method change the length of an array.

for (var i = 0; i < 10; i++) {
    document.writeln(myarray.pop(i));
}

Complete code is below

var myarray = [];
document.writeln("<H4> Adding Elements In Array Push and Pop</H4>");
document.writeln("<br/>");
for (var i = 0; i < 10; i++) {
    var val = (i + 1) * 2;
    myarray.push(val);
    document.writeln('myarray[' + i + '] =' + val);
    document.writeln("<br/>");
}

document.writeln("<H4> Showing Elements In Array</H4>");
document.writeln("<br/>");

for (var i = 0; i < 10; i++) {
    document.writeln(myarray.pop(i));
    document.writeln("<br/>");
}

The output of the above code is like below

JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

Shift and Unshift Method of an array in JavaScript

Unshift method:

This method is like a push method in the array means it adds a new item in array but the difference is that push method adds an element at last of an array and unshift adds elements at the beginning of an array.

var myarray = [4,3];
    myarray.unshift(10);
    document.writeln('myarray[] =' + myarray); // myarray[] =10,4,3

Shift Method:

This method is alike of pop method but it removes the item from the beginning of an array .

var myarray = [10,4,3];
document.writeln(myarray.shift()); // 10

complete code of this

var myarray = [4,3];
document.writeln("<H4> Adding Elements In Array Using Shift and UnShift</H4>");

document.writeln("<br/>");
    myarray.unshift(10);
    document.writeln('myarray[] =' + myarray);
    document.writeln("<br/>");


document.writeln("<H4> removing Elements In Array</H4>");
document.writeln("<br/>");

    document.writeln(myarray.shift());
    document.writeln("<br/>");

The output of above code is below

JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

Mutator Methods in JavaScript:

In JavaScript there are several methods which can be used with array object in JavaScript. In which some methods modify the array object while another method did not modify that array object. The methods which modify the array object is mutator methods and which not modify the object is called non-mutator methods.

Examples of non-mutator methods below:

Contains, indexOf,Length

Examples of mutator methods like

  • Push
  • Pop
  • Unshift
  • Shift
  • Reverse
  • Sort
  • Splice

Sort Method of Array:

It will sorts elements in array. By default sort method sort the values by converting them into strings and then it will compare these strings.

This will work well for the string but not for numbers.

var array = ["Sagar", "Jaybhay", "Ram", "Lakhan"];
document.writeln("Before sort an array :==> "+array);
array.sort();

document.writeln("<br/>");
document.writeln("<br/>");
document.writeln("After sort the array :==> "+array);

Output of above code is looks like below

JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

For Number see below code and output

var array = [10,1,12,11,3,2];
document.writeln("Before sort an array :==> " + array);
array.sort();

document.writeln("<br/>");
document.writeln("<br/>");
document.writeln("After sort the array :==> " + array);

the output of this code

JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

If you simply try to sort a numeric array using the sort() method it will not work, because the sort() method sorts the array elements alphabetically. But, you can still sort an array of integers correctly through utilizing a compare function, as shown in the following example:

var array = [10,1,12,11,3,2];
document.writeln("Before sort an array :==> " + array);
array.sort(function(a, b) {
    document.writeln("<br/>");

    document.writeln("Value of a = "+ a +"|| and value of b = "+b+" || "+(a-b));
    document.writeln("<br/>");
    return a - b;
} );

document.writeln("<br/>");
document.writeln("<br/>");
document.writeln("After sort the array :==> " + array);

the output of the above code is

JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

Now how compare function works in array sort function

Array.sort(function(a,b){return a-b})

The outcome of this inside function is only 3 types of output

  1. Positive:- it means a is greater than b
  2. Negative:- it means a is smaller than b
  3. Zero:- it means both are equal

This will sort the array in ascending manner but if you want to sort array in descending manner you need to apply reverse function after that.

var array = [10, 1, 12, 11, 3, 2];
document.writeln("Before sort an array :==> " + array);
array.sort(function (a, b) {
    return a - b;
}).reverse();

document.writeln("<br/>");
document.writeln("After sort the array :==> " + array);

or you can simply make a change in compare function like below change position of a and b in return statement.

JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

Methods in array elements

Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin It copies the part of the given array with its own elements and returns the modified array.
every() It determines whether all the elements of an array are satisfying the provided function conditions.
fill() It fills elements into an array with static values.
filter() It returns the new array containing the elements that pass the provided function conditions.
find() It returns the value of the first element in the given array that satisfies the specified condition.
findIndex It returns the index value of the first element in the given array that satisfies the specified condition.
forEach It invokes the provided function once for each element of an array.
includes It checks whether the given array contains the specified element.
indexOf It searches the specified element in the given array and returns the index of the first match.
join() It joins the elements of an array as a string.
lastIndexOf It searches the specified element in the given array and returns the index of the last match.
map() It calls the specified function for every array element and returns the new array
pop() It removes and returns the last element of an array.
push() It adds one or more elements to the end of an array.
reverse It reverses the elements of given array.
shift() It removes and returns the first element of an array.
slice() It returns a new array containing the copy of the part of the given array.
sort() It returns the element of the given array in a sorted order.
splice() It add/remove elements to/from the given array.
unshift It adds one or more elements in the beginning of the given array.

Filter Method in JavaScript array:

The filter() method creates a new array and populates that array with all elements which meets the condition which is specified in callback function.

Synatx:

Array.filter(callbackfunction[,arg])

Callback function: It is required in filter function and it gets called for each element of array. If the function returns true, the element is kept else not.

Arg: it is optional and it is object to which this keyword is referred in callback function.

Filter mehod calls the callback function every time for each element in array. Suppose call back function returns false for every element in array then the length of an array is 0;

Callback Function Syntax:

 Function callbackfunction(value,index,array)

  • Value- is value of array element
  • Index:- index position of elements in array
  • Array:- source array object
var array = [10, 20, 21, 11, 9, 122, 23, 31, 13, 221, 22, 321, 412, 123];


document.writeln("orignal array:- " + array);
document.writeln("<br/>");

function  isOdd(value,index,array) {
    if (value % 2 != 0) {
        return true;
    } else {
        return false;
    }
}
document.writeln("<br/>");

document.writeln("filtered array :-"+array.filter(isOdd));

the output of the above code is below image

JavaScript Array, Know About JavaScript Array, Sagar Jaybhay

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *