Header Ads Widget

JavaScript Arrays

 This post will introduce you about JavaScript Arrays. 

What is an JavaScript array?

An array is non-primitive data type store multiple values in one variable. An array values are also called elements. In array all the values are stored in indexes and this indexes are in ascending order starting with zero.

For example

let fruits=[apple, banana, cherry, mango, plums];


JavaScript arrays element and indexing
JavaScript array indexing 

In example, fruits is an array of 5 different fruits. Each fruit has stored in unique index.

How to create an array in JavaScript?

An array is created using two ways.

1. Array literals
2. Array constructor

Creating array by array literals 

In array literals array elements are defined in square bracket [] separated by comma.

Syntax 

var_type array _name=[element 1, element 2, element 3,];

Examples of array literals 

Example 1: odd_no array consists of 5 odd numbers. 

let odd_no=[1,3,5,7,9,11];

Example 2: alpha array is empty array which have no elements.

let alpha=[];

Example 3: stud_data array consists of mixed data type of elements.

const stud_data=[1,Arav Sahani,8-a];

Example 4: String array

const vowels=[a,e,i,o,u];

Example 5: First fruits array is created then all values are assigned to particular indexes.

const fruits=[];
fruits [0]=apple;
fruits [1]=banana;
fruits [2]=mango;
fruits [3]=cherry;
fruits [4]=plums;

Creating array by array constructor 

In second method array is created by new keyword.

Syntax

var_type array _name=new Array(element 1, element 2, element 3,);

Examples of array constructor

Example 1: Empty array 

const emtpy_array=new Array();

Example 2: num array with intial size 10.

let num=new Array(10);

When you already know size of array then create array with size in array constructor.

Example 3: An odd array with six odd numbers.

const odd=new Array (1,3,5,7,9,11);

Note:- It is recommended that always use first method array literals to declare array without complications.

How to access array elements?

To access array elements their index is used. To access array elements specify array name with particular indexes wrapped in square brackets [].

Syntax

array _name[index_of_array_element]; 

Example

const fruits=["apple","banana","mango","cherry","plums"];
document.write(fruits[3]);
// cherry 
//If you want to access whole array then only specify array name.
document.write (fruits);
// apple,banana,mango,cherry,plums

How to find number of elements in array in JavaScript ?

In JavaScript length property is used to find length of an array. See in example how to use it.

Example

const season=[Summer,Winter,Rainy];
console.log(season.length); // 3

Another use of length property is you can access array elements in descending order.

Example

 Accessing second last element of array.


console.log(season[season.length-2]);
// winter 

Insertion operation on array 

Inserting an element at beginning of array

You can add element at beginning in array by using unshift() method.

Example 

const animal=[cow,buffelo,dog,cat];
document.write(<b> output before insertion opeartion</b><br>,animal,<br>);
animal.unshift(goat);
document.write(<b>output after inserting element at beginning of array</b> <br>,animal);

Output
Inserting an element at beginning of array
Inserting an element at beginning of array

Inserting element at the end of array

You can add element at the end of the array using two ways. First is by using push() method and second one is by length property.

Example 1: 

insert element at end of array using push () method.

const animal=[cow,buffelo,dog,cat];
document.write(<b> output before insertion opeartion</b><br>,animal,<br>);
animal.push(rabbit);
document.write(<b>output after inserting element at end of array with push()</b> <br>,animal,<br>);

Output
Inserting an element at end of array using push () method
Inserting an element at end of array using push () method 

Example 2:

 insert element at end of array using length property.

animal[animal.length]=sheep;
document.write(<b>output after inserting element at end of array with length property</b> <br>,animal,<br>);

Output 
Inserting an element at end of array using length property
Inserting an element at end of array using length property 

Deletion operation on array 

Delete/Remove element from beginning of array

The shift() method is used to remove element from beginning of array.

Example

deletes first element from array

const animal=[cow,buffelo,dog,cat];
document.write(<b> output before deletion opeartion</b><br>,animal,<br>);
animal.shift();
document.write(<b>output after removing element from beginning of array with shift()</b> <br>,animal,<br>);

Output
Remove element from beginning of array (shift())
Remove element from beginning of array (shift())

Delete/Remove element from end of array

pop() method removes element at end of the array.

Example 

Removes last element.

animal.pop();
document.write(<b>output after removing element from end of array with pop()</b> <br>,animal,<br>);

Output
Removes element from end of array using pop()
Removes element from end of array using pop()

How to change array element?

An array element can be changed by accessing index value of that element.

Example

Changes the value of 2nd index with new value.

const flowers=[rose,lotus,sun flower,jasmine];
document.write(<b> list of flowers</b><br>,flowers,<br>);
flowers[2]=tulip;
document.write(<b> changing value of index 2</b><br>,flowers);

Output
Changing array element
Changing array element 

How to find index of array element?

You can find index of particular element in array using indexOf() method.

Example
Returns the position of element in which it stored.

const flowers=[rose,lotus,sun flower,jasmine];
let indx=flowers.indexOf(jasmine);
document.write(<b> the index of jasmine is:</b><br>,indx); 
// the index of 'jasmine' is: 3

How to check the variable is array or not?

The Array.isArray() method is used to check whether the variable is array or not. If variable is array returns true otherwise false.

Example

const flowers=[rose,lotus,sun flower,jasmine];

console.log(Array.isArray(flowers)); //true 

Merge/join array elements into one string using join() method 

The join() method is JavaScript built-in method introduced in 1997 in ESMA script 1.

You can join/merge an array elements with or without seperator.

Let's understand with example

In example, name array is taken with single characters and merged without seperator.


const name=["T","o","n","y"];
const mergearray=name.join("");
document.write("<b>Array elements before joining</b><br>",name);
document.write("<br><b>Array elements after joining</b><br>",mergearray);

If you don't want seperator use ("") with no space in between.

Output
Array join() method (joining array elements into string)
Array join() method (joining array elements into a string)

Another example of joining array elements.

const menu=["Home","About", "Services","Contact"];
const joinstr=menu.join("/");
document.write("<b>Array elements before joining</b><br>",menu);
document.write("<br><b>Array elements after joining</b><br>",joinstr);

Here, two array elements are joined by "/".

Output 
Array join () method
Array join () method 

Multidimensional array creation

You can create a multidimensional array by using two ways similar to an array.

1) Array literals
2) Array constructor 

Creating multidimensional array by Array literals

Syntax

var_type array _name= [
[element 1, element 2,... element n],
[element 1, element 2,... element n],
[ element 1, element 2,... element n]
];

Where element 1 has an index value of 0, 2 has an index value of 1, and so on.

Or

var_type array1= [
[element 1, element 2,... element n];
var_type array2= [
[element 1, element 2,... element n];
var_type array3= [
[element 1, element 2,... element n];
var_type array_name= [
[array1,array2,array3]
];

Example

A multidimensional array of cars having 2 array elements, car name, and price.


let cars=[
[BMW,10000000],
[Nexa,2000000],
[KIA,2500000]
];

Or you can also create like this one 

let car1= [BMW,10000000];
let car2= [Nexa,2000000];
let car3= [KIA,2500000];
let cars= [car1, car2, car3];

Creating multidimensional array by Array constructor

Syntax 

var_type array_name=Array([element 1,  element 2, element n],
[element 1,  element 2, element n],
[element 1,  element 2, element n],);

Where all arrays are defined by Array() method.

Example 

A multidimensional array of students with three array elements : roll no, name,  and class.

let students=[
[1,Lisa, first],
[2,Natasha, distinction],
[3,Hody, third]
];

How multidimensional array stored?

Let’s understand multidimensional array storage with students array.


Storage of multidimensional array
Storage of multidimensional array 


Accessing elements of multidimensional array

You can access multidimensional array similar as one dimensional array but with two or more extra indices.

Syntax 

array _name[index_no][index_no];

Example

Accessing car array

console.log(cars[2][0]); //KIA

Accessing students array

document.write(students);
//1,Lisa,first,2,Natasha,distinction,3,Hody,third


Summary

This post covered basic information about one dimensional array and multidimensional array. An array is a list of values and each value has their unique index. When you declare an array use let or const. It is recommended that declare array with const. The methods used for array operations are built-in methods in JavaScript.

Post a Comment

0 Comments