A quick guide to JavaScript Arrays

Fri, Nov 15, 2019

Read in 2 minutes

We can say JavaScript arrays as a special kind of objects. In this article, we are going to explore how to create JavaScript arrays and multidimensional arrays, how to add or remove elements in the array and how to use array methods filter, map and reduce.

How to create an array

Let NumberArrays =[1,2,3,4,5];

Even, you can create an empty array and add elements later.

Let colorsArr =[]; colorsArr [0]="Red”; colorsArr [1]="Blue”; colorsArr [2]="Brown”; colorsArr [3]="Orange”;

Create an array with property and attribute name

let EmpArray ={ name:“Bob”,age:“35”,salary:“$8000”};

If you want to add a property after initializing the array,

EmpArray.country=[US];

How to create multidimensional-array:

Multidimensional arrays are arrays within the arrays in javascript.

Let Multiarray =[]; //this is the empty array. //For index 0 ,you can insert an array , Multiarray [0] =[1,2,3]; //likewise ,you can add an array for other index also , Multiarray [1]=[4,5,6]; Multiarray [2]=[7 8 9];

How to iterate the array:

1.for loop 2.for …in 3.for …of

Traditional for loop :

var length=colorsArr.length;
 for(var i=0;i<length;i++){
     console.log("values "+colorsArr[i]);
	}

For in Loop

for(key in colorsArr) {
    console.log("values "+colorsArr[key]);
    }

Here the key is the index value.

For of loop

for(item of colorsArr){
  console.log("item "+item);
	}

Here the item denotes the individual array elements.

Array methods to add/delete an element

Push – add an element at the end of the array.

Pop – removes the last element of the array

colorsArr.push(‘mango’); colorsArr.pop();

Here the push method adds the ‘mango’ at the end and pop removes the last element ‘mango’.

unshift – add an element at the beginning of the array.

Shift -removes the first element of the array.

colorsArr.unshift(‘mango’); colorsArr.shift();

How to use map, reduce, filter methods:

FILTER

The filter method called for every element of the array and returns true if the given condition is a pass.

let students = [ {id: 1, name: “John”,grade:‘A’}, {id: 2, name: “bob”,grade:‘B’}, {id: 3, name: “mary”,grade:‘B’}, ]; resultStudent = students.filter(item=>(item.grade=='B’)); //this returns the array of students with B grade.

MAP

The map method transforms the array into a new array based on the condition given.

let colorsArr =[red ,blue,yellow]; colorsArrMap =colorsArr.map(item=>(item+'color’));

output: colorsArr=[redcolor,bluecolor,yellowcolor]

REDUCE METHOD

Reduce method reduces the array elements as a single element with the callback function statement.

let NumberArrays =[1,2,3,4,5]; NumberArrayReduce =NumberArrays.reduce((currentvalue, sum) => currentvalue + sum); //output:10