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)

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]);

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]);

Array 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]);

Array 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]);

Array Traversal For Each Loop

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

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);
}

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 Filtering

The filter() method filters and extracts the element(s) of an array satisfying the provided condition. It doesn't change the original array.

let status=["Completed", "InProgress","Ordered","Completed","Ordered"];
let val="Completed";
let filtered=status.filter(function(item){
       if(val===item)
       return val;
 });

console.log(filtered);
console.log(filtered[0]);

Array Map

The map() method will transform the array

let transformArray = [1,2,3,4].map((n)=>{
    return n*n;
})
console.log(transformArray);

Get the full name from the first and last names using map concept.

let persons = [
    {firstname : "Malcom", lastname: "Reynolds"},
    {firstname : "Kaylee", lastname: "Frye"},
    {firstname : "Jayne", lastname: "Cobb"}
  ];

function getFullName(item) {
    let fullname = [item.firstname,item.lastname].join(" ");
    return fullname;
}
    
let fullnames= persons.map(getFullName);
console.log(fullnames);

Array Reduce

Let's say we have an array of amounts and want to add them all up.

const euros = [29.76, 41.85, 46.5];
const sum = euros.reduce((total, amount) => total + amount); 
console.log(sum); 

This will print 118.11

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