JS Array

JavaScript

Share


In this tutorial we will learn about JavaScript array.

Lets say we want save name of 5 fruits. We can solve this by creating 5 variables, one for each fruit.

var fruits1 = "Apple";
var fruits2 = "Orange";
var fruits3 = "Mango";
var fruits4 = "Banana";
var fruits5 = "Guava";

But there are some problems in this approach. First, we are creating too many variables. Second, it is hard to work with them efficiently. Imagine, we want to add 10 more fruits. Then in this approach we have to again create 10 more variables.

To solve this problem we take help of an array.

What is an array?

An array is a variable that holds multiple values under same name.

How to define an array?

We define array by creating an instance of Array object.

Syntax

var arrayName = new Array(element0, element1, element2);

In the following example we are creating an array having 5 elements.

var fruits = new Array("Apple", "Orange", "Mango", "Banana", "Guava");

Alternative way to create an array

There is an alternative way to create an array using [ ] square brackets.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

How to find number of elements in an array?

We use the length property to find the number of elements in an array.

//create array
var fruits = new Array("Apple", "Orange", "Mango", "Banana", "Guava");

//print length
console.log(fruits.length);	//this will print 5

How to access value of an array?

Values stored in an array are called elements of the array. We use the array index to access the elements. Array indexing starts from 0.

So, if an array has 5 elements then the first element is at index 0, second element is at index 1 and the last element (5th element) is at index 4.

In the following example we are creating an array having 5 elements. Then using for loop we are printing the elements of the array.

var fruits = new Array("Apple", "Orange", "Mango", "Banana", "Guava");

var len = fruits.length;	//no. of elements of the array

//print elements of the array
for (var i = 0; i < len; i++) {
	console.log(fruits[i]);
}

Output

Apple
Orange
Mango
Banana
Guava

More ways to create arrays

Allocate space for the array and fill the space later

In the following example we have allocated space for a array having 5 elements but we are filling it later.

//allocate space for array of 5 elements
var fruits = new Array(5);

//fill the array
fruits[0] = "Apple";
fruits[1] = "Orage";
fruits[2] = "Mango";
fruits[3] = "Banana";
fruits[4] = "Guava";

So, the first element is at index 0, second element is at index 1, and the last element is at index 4.

Create instance of Array object without size

In this we create an instance of the Array object and then later add the elements.

//create instance
var fruits = new Array();

//add elements
fruits[0] = "Apple";
fruits[1] = "Orage";
fruits[2] = "Mango";
fruits[3] = "Banana";
fruits[4] = "Guava";

Note! If we assign an element to a higher index then index before it will be auto created.

In the following example we are creating an instance of Array object without size. Then we are adding an element at index 4. This will make the array of size 5 automatically.

//create array
var fruits = new Array();

//add element at index 4
fruits[4] = "Guava";

//find length of the array
var len = fruits.length;

console.log(len);	//this will print 5

//print elements of the array
for (var i = 0; i < len; i++) {
	console.log(fruits[i]);
}

Output

5
undefined
undefined
undefined
undefined
Guava

Note! In the above array that are not assigned any value are set to undefined.

Array Methods

concat( )

We use the concat( ) method to concatenate two arrays into a new one.

In the following example we are concatenating two arrays.

var arr1 = ["Apple", "Orange"];
var arr2 = ["Mango", "Banana", "Guava"];

var fruits = arr1.concat(arr2);

console.log(arr1);
console.log(arr2);
console.log(fruits);

Output

["Apple", "Orange"]
["Mango", "Banana", "Guava"]
["Apple", "Orange", "Mango", "Banana", "Guava"]

In the above code we are concatenating arr2 after arr1 and assigning the resultant array to fruits.

join( )

We use the join( ) method to combine the elements of the array into a string separated by a character that we pass as parameter to the method.

If no separator character is passed then , comma is used as default separator.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

var fruits_str = fruits.join("-");

console.log("Fruits array");
console.log(fruits);

console.log("Fruits string");
console.log(fruits_str);

Output

Fruits array
["Apple", "Orange", "Mango", "Banana", "Guava"]
Fruits string
Apple-Orange-Mango-Banana-Guava

In the above code we have an array fruits which we are converting into a string using the join() method and we are using - hyphen as the separator.

pop( )

We use the pop( ) method to remove the last element from the array. We can save the popped element in a variable.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Before pop");
console.log(fruits);

var popped_fruit = fruits.pop();

console.log("After pop");
console.log(fruits);

console.log("Popped element: " + popped_fruit);

Output

Before pop
["Apple", "Orange", "Mango", "Banana", "Guava"]
After pop
["Apple", "Orange", "Mango", "Banana"]
Popped element: Guava

In the above code we have an array fruits and using the pop method we are removing the last element "Guava".

push( )

We use the push( ) method to add an element to the end of an array. We can save the popped element in a variable.

var fruits = ["Apple", "Orange", "Mango", "Banana"];

console.log("Before push");
console.log(fruits);

fruits.push("Guava");

console.log("After push");
console.log(fruits);

Output

Before push
["Apple", "Orange", "Mango", "Banana"]
After push
["Apple", "Orange", "Mango", "Banana", "Guava"]

In the above code we have an array fruits and using the push method we are adding an element "Guava" at the end of the array.

reverse( )

We use the reverse( ) method to reverse the order of the elements in an array.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Before reverse");
console.log(fruits);

fruits.reverse();

console.log("After reverse");
console.log(fruits);

Output

Before reverse
["Apple", "Orange", "Mango", "Banana", "Guava"]
After reverse
["Guava", "Banana", "Mango", "Orange", "Apple"]

In the above code we have an array fruits and using the reverse method we are reversing the order of the elements.

shift( )

We use the shift( ) method to remove the first elements of an array. The removed element is returned by this method which can be saved in a variable.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Before shift");
console.log(fruits);

var elem = fruits.shift();

console.log("After shift");
console.log(fruits);

console.log("Element shifted");
console.log(elem);

Output

Before shift
["Apple", "Orange", "Mango", "Banana", "Guava"]
After shift
["Orange", "Mango", "Banana", "Guava"]
Element shifted
Apple

In the above code we have an array fruits and using the shift method we are removing the first element of the array.

unshift( )

We use the unshift( ) method to add elements at the beginning of an array. The method returns length of the new array after adding the elements.

var fruits = ["Mango", "Banana", "Guava"];

console.log("Before unshift");
console.log(fruits);

var new_length = fruits.unshift("Apple", "Orange");

console.log("After unshift");
console.log(fruits);

console.log("New length");
console.log(new_length);

Output

Before unshift
["Mango", "Banana", "Guava"]
After unshift
["Apple", "Orange", "Mango", "Banana", "Guava"]
New length
5

In the above code we have an array fruits and using the unshift method we are adding 2 elements at the beginning of the array.

slice( )

We use the slice( ) method to slice a specified portion of the array. This will return a new sliced array.

Syntax

array_name.slice(start, stop);

array_name is the array that we want to slice. start is the starting index from where we want to start slicing elements. stop is the index number that comes after the last element that we want to slice.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Before slice");
console.log(fruits);

var sliced_array = fruits.slice(1, 3);

console.log("After slice");
console.log(fruits);

console.log("Sliced array");
console.log(sliced_array);

Output

Before slice
["Apple", "Orange", "Mango", "Banana", "Guava"]
After slice
["Apple", "Orange", "Mango", "Banana", "Guava"]
Sliced array
["Orange", "Mango"]

In the above code we have an array fruits and using the slice method we are slicing elements. The start is set to 1. This means we are slicing from index 1. stop is the set to 3. This means we are slicing till index (3-1) i.e., 2. So, the slices elements are ["Orange", "Mango"].

splice( )

We use the splice( ) method to remove and replace elements from the array.

Syntax

array_name.splice(start, numberOfElem, new_elem);

array_name is the array that we want to splice. start is the starting index from where we want to start splicing elements. numberOfElem is the number of elements that we want to splice. new_elem are the new elements that we want to add.

Remove N elements

In the following example we are going to splice 2 elements from index 1.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Before splice");
console.log(fruits);

var splice_array_elem = fruits.splice(1, 2);

console.log("After splice");
console.log(fruits);

console.log("Spliced array elements");
console.log(splice_array_elem);

Output

Before splice
["Apple", "Orange", "Mango", "Banana", "Guava"]
After splice
["Apple", "Banana", "Guava"]
Spliced array elements
["Orange", "Mango"]

Remove all elements from index N

In the following example we are going to splice all elements from index 1.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Before splice");
console.log(fruits);

var splice_array_elem = fruits.splice(1);

console.log("After splice");
console.log(fruits);

console.log("Spliced array elements");
console.log(splice_array_elem);

Output

Before splice
["Apple", "Orange", "Mango", "Banana", "Guava"]
After splice
["Apple"]
Spliced array elements
["Orange", "Mango", "Banana", "Guava"]

Remove N elements from index I then add new elements

In the following example we are going to splice 2 elements from index 1 then add 2 new elements.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Before splice");
console.log(fruits);

var splice_array_elem = fruits.splice(1, 2, "Strawberry", "Grape");

console.log("After splice");
console.log(fruits);

console.log("Spliced array elements");
console.log(splice_array_elem);

Output

Before splice
["Apple", "Orange", "Mango", "Banana", "Guava"]
After splice
["Apple", "Strawberry", "Grape", "Banana", "Guava"]
Spliced array elements
["Orange", "Mango"]

sort( )

We use the sort( ) method to arrange the elements of the array in alphabetical order.

In the following example we are sorting the array elements.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Before sort");
console.log(fruits);

fruits.sort();

console.log("After sort");
console.log(fruits);

Output

Before sort
["Apple", "Orange", "Mango", "Banana", "Guava"]
After sort
["Apple", "Banana", "Guava", "Mango", "Orange"]

toString( )

We use the toString( ) method to combine the elements of an array separated by comma. This will return a string.

In the following example we are combining the elements of the array into string separated by comma.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Before toString");
console.log(fruits);

var fruits_str = fruits.toString();

console.log("After toString");
console.log(fruits);

console.log("Fruits string");
console.log(fruits_str);

Output

Before toString
["Apple", "Orange", "Mango", "Banana", "Guava"]
After toString
["Apple", "Orange", "Mango", "Banana", "Guava"]
Fruits string
Apple,Orange,Mango,Banana,Guava

Some more methods

filter( )

We use the filter( ) method to create a new array containing elements that passed the filter we created.

In the following example we will get a new array having elements greater than 10.

//filter function
function biggerThan10 (val) {
	return val > 10;
}

var arr = [1, 10, 20, 5, 30];

var filtered_array = arr.filter(biggerThan10);

console.log(filtered_array);

Output

[20, 30]

In the above code we are using the biggerThan10() function to filter elements of the arr array. If the element is greater than 10 then function biggerThan10 will return true and that element will be added to the filtered_array array.

forEach( )

We use the forEach( ) method to execute a function for every element of the array.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

//print element
fruits.forEach(function(elem){
	console.log(elem);
});

Output

Apple
Orange
Mango
Banana
Guava

In the above code we are using the forEach() method to print all the elements of the fruits array.

every( )

We use the every( ) method to check if all the elements of the array pass a given test. The method will return true if all elements passed the test, false otherwise.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

function checkType (elem) {
	return (typeof elem === "string");
}

console.log("Is type of all elements string? " + fruits.every(checkType));

Output

Is type of all elements string? true

some( )

We use the some( ) method to check if some of the elements of the array pass a given test. The method will return true if some elements passed the test, false if none passed the test.

var arr = ["Apple", 1, "Mango", "Banana", "Guava"];

function checkType (elem) {
	return (typeof elem === "number");
}

console.log("Is type of some elements number? " + arr.some(checkType));

Output

Is type of some elements number? true

indexOf( )

We use the indexOf( ) method returns the first index at which the given element is found. -1 if not found.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Guava"];

console.log("Index of Mango: " + fruits.indexOf("Mango"));

Output

Index of Mango: 2

lastIndexOf( )

We use the lastIndexOf( ) method returns the highest index at which the given element is found. -1 if not found.

var fruits = ["Apple", "Orange", "Mango", "Banana", "Mango"];

console.log("Last index of Mango: " + fruits.lastIndexOf("Mango"));

Output

Last index of Mango: 4