Skip to content

07 Arrays

Biswajit Sundara edited this page May 1, 2023 · 3 revisions

JavaScript arrays are used to store multiple values in a single variable.

  • This can contain values of different data types however best practice is to store similar data type values.
  • Array index starts from 0 (zero)

1. Array Properties

Array Declaration

We can assign the values directly to the array variable or we can first declare the array variable and later assign the values.

  • let cars = ["Saab", "Volvo", "BMW"];
  • let fruits = new Array("mango", "apple", "grape");
  • let city=[];
  • let movies=[3];
  • Avoid using the new Array() approach as that's a bad practice.

Array Length

let names=["Anushka","Kareena","Katrina"]
let len= names.length;
console.log("Name count= "+len);

Array Index

The array index starts from zero [ 0 ] so if it has 3 elements then the index will be 0,1,2

let movies=[3];
movies[0]="Frozen";
movies[1]="Harry Potter";
movies[2]="Kungfu Panda";
for (i=0;i<movies.length;i++)
console.log(movies[i]);

2. Creating Array

Example 1

Create array by assigning the values and use for loop to traverse.

let cars = ["Saab", "Volvo", "BMW"];
for (i=0;i<cars.length;i++)
console.log(cars[i]);

Example 2

Create array by using the new Array() and use for each loop to traverse.

let fruits = new Array("mango", "apple", "grape");
for (let fruit of fruits)
console.log(fruit);
console.log("First element="+ fruits[0]);

Example 3

Create array by assigning values based on the index.

let city=[];
city[0]='Chennai';
city[1]='Bangalore';
city[2]='Hyderabad';
for(i=0;i<city.length;i++)
console.log(city[i]);

3. Array Traversal

For Each Loop

let tools=["Cypress","Karate","Selenium"];
tools.forEach((tool,index)=>{
  console.log(index+'---'+tool);
});

For Of

  • for...of is a new loop statement introduced in ES6
  • It simplifies iterating over iterable objects such as arrays, strings, maps, sets, etc.
const myArray = ['apple', 'banana', 'orange'];

for (const element of myArray) {
  console.log(element);
}

4. Dynamic Array with Push/Pop

We can first declare the array and then insert the values using push() and remove element using pop()

const fruits = [];

fruits.push("Apple");
fruits.push("Mango");
fruits.push("Grape");

for(let fruit of fruits){
    console.log(fruit);
}

//Removes the last element
fruits.pop();

for(let fruit of fruits){
    console.log(fruit);
}

5. Check if Array

let x=5;
let flag= Array.isArray(city);
console.log("city is an array= " + flag);    //This will return true

flag= Array.isArray(x);
console.log("x is an array= " +flag);        //This will return false

flag= fruits instanceof Array;  
console.log("fruits is an array= " +flag);   //This will return true

Array Element Data Type

let arr=[];
arr[0]="Biswajit";
arr[1]=10;

let flg= typeof arr[0];
console.log("arr[0] is of type= "+flg);  //This will return string

flg= typeof arr[1];
console.log("arr[0] is of type= "+flg); //This will return number

Array concatenation

We can merge multiple arrays and create one array.

 let stars=["Ayushman","Akshay","Ranveer"];
 let actors=["Paresh","Anupam","Nasir"];
 let actress=["Kareena","Priyanka","Aishwarya"];

 let starcast= stars.concat(actors,actress);
 for(i=0;i<starcast.length;i++)
 console.log(starcast[i]);

Array Entries

Create an Array Iterator object, and create a loop that iterates each key/value pair

let brands=["adidas","Rebok","Puma"];
let itr=brands.entries();
for(let ele of itr)
console.log(ele);

------------------------
OUTPUT
[ 0, 'adidas' ]
[ 1, 'Rebok' ]
[ 2, 'Puma' ]

Array Includes

The includes() method checks whether the elemenet exists in the array or not. It returns true if an array contains the element, otherwise false.

let pandavas=["Yudhistir","Bhima","Arjuna","Nakul","Sahdev"];
let flag= pandavas.includes("Arjuna");
console.log("Arjuna is a pandav " +flag);

flag= pandavas.includes("Duryodhana");
console.log("Duryodhana is a pandav " +flag);

Index Of

The indexOf() method is used to search the position of a particular element in a given array. The index of first element is always start with zero. Returns -1 if the element is not found. If there are multiple matching elements, it returns the first element that's found. You can use lastIndexOf() method if you want to get the last matching element.

let nonveg=["checken","fish", "prawn"];
let index=nonveg.indexOf("fish");
console.log("Index of fish "+index);

index=nonveg.indexOf("crab");
console.log("Index of crab "+index);

Object Array

const persons = [
    {
        name:"Alex",
        age:"21"
    },
    {
        name:"John",
        age:"31"
    }
];

for (let i=0;i<persons.length;i++){
    console.log(persons[i].name);
    console.log(persons[i].age);
}

Clone this wiki locally