Arrays in JavaScript

An array is a data type that can hold multiple values stored in a contiguous memory locations. Different values of arrays are called its elements. Array elements can be of any data type.

How to create arrays in JavaScript?

Arrays can be created using the new keyword followed by Array() object constructor. We will discuss objects and constructor later. Also arrays can be created using square brackets ([]).

Syntax

new Array(value1, value2, value3,...)

or

//this one is more simple and precise

[value1, value2, value3,...]

Example

<script>

var arr = new Array('one', 'two', 'three'); //string array

var arr2 = [1, 2, 3]; //numeric array

var arr3 = []; //empty array

</script>

Accessing array elements in JavaScript

You can refer to different array elements using the same array name with an index number. When you create an array all of its elements are stored with an index number. Index number begins with 0 by default if you don't define it. So first element in an array has index number 0, second element has 1 and so on.

Syntax

array_name[index]

Example

<script>

var arr = new Array('one', 'two', 'three');

document.write(arr[0]); //outputs one
document.write("<br />);

document.write(arr[1]); //outputs two
document.write("<br />);


document.write(arr[3]); //outputs three
document.write("<br />);

</script>

In case if you define an array with some index value, the next element is going to be stored at an index greater than the previous index.

Size of an Array

Size of an array means the number of elements stored inside an array. length property is used to get the size of an array.

Syntax

array_name.length

Example

<script>

var arr = ['one', 'two', 'three'];

var size = arr.length; //3

document.write(size);

</script>

Looping through an array

Loops are very much related to arrays. You can go through all the elements of an array using loops. Here's an example to demostrate how?

Example

<script>

var arr = ['one', 'two', 'three'];
for(var i=0;i<arr.length;i++)
{
	document.write(arr[i] + " ");
	//one two three
}

</script>

Variable i is initialized to 0. Remember array begins with index 0 (unless you specify some other index to begin with).

for in loop

for in is an special loop in JavaScript to loop through all the elements of array without knowing the size of it.

Syntax

for(value in array)
{
	//statements
}

Value is a variable that will store array elements one by one until it access all of them.

Example

<script>

var arr = ['one', 'two', 'three'];

for(var i in arr)
{
	document.write(arr[i] + " ");
}

</script>

Adding elements in Array

Using index

You can add array elements using following syntax:

array[index] = value;

If index at which you are trying to add an element is already present then new element will replace the old element.

Example

<script>

var arr = ['one', 'two', 'three'];
arr[1] = 2;
document.write(arr); //one,2,three
document.write("<br />");

var arr2 = []; //defines empty array
arr2[1] = 3; //adds value to index 1
document.write(arr2); //outputs ,1

</script>

push() method

push method is used to add elements at the end of an array and it returns the new length.

Syntax

array_name.push(value1, value2,...)

Example

<script>

var arr = ['one', 'two', 'three'];
arr.push("four"); //4
document.write(arr); //outputs one,two,three,four
document.write("<br />");


arr.push("five","six"); //6
document.write(arr); //outputs one,two,three,four,five,six

</script>

unshift() method

unshift method adds an element at the very beginning of an array. It returns new length.

Syntax

unshift(value1, value2,...)

Example

<script>

var arr = ['one', 'two', 'three'];
arr.unshift("zero"); //4
document.write(arr); //outputs zero,one,two,three

</script>

Deleting Elements from Array

Using length

length property can be used to delete elements from the end.

Syntax

array_name.length -= value;

Here value represents the number of elements you want to delete.

Example

<script>

var arr = [1,2,3,4,5];
document.write("original array: " + arr);
document.write("<br />");

arr.length -= 2;
document.write("after deletion: " + arr);

</script>

pop() method

pop method is used to delete an element from the end of an array. It will return the last element of an array that gets deleted.

Syntax

array_name.pop()

Example

<script>

var arr = [1,2,3];
document.write(arr.pop()); //outputs 3
document.write("<br />");

document.write(arr); //outputs 1,2

</script>

shift() method

shift method is used to delete an element from the beginning of an array. It returns the first element of an array that gets deleted.

Syntax

array_name.shift()

Example

<script>

var arr = [1,2,3];
arr.shift(); //1
document.write(arr); //outputs 2,3

</script>

Getting arbitrary elements from an array

slice() method

slice method is used to get elements from an array between specified indexes passed to it as parameters.

Syntax

array_name.slice(start, [end])

The element at the 'end' index is not included. If end index is not specified then the result will be from start index till the end of the array.

Example

<script>

var arr = [1,2,3,4,5];
var sub = arr.slice(1, 4); //2,3,4
document.write(sub);
document.write("<br />");

sub = arr.slice(1); //2,3,4,5
document.write(sub);

</script>

splice() method

splice method is used to replace elements from an array beginnig at a specified index. It returns the removed elements.

Syntax

array_name.splice(position, number, value1, value2,..)

position specifies the index position from where elements should be started to get replaced.

number specifies how many elements are to be replaced.

values are the new values to be placed instead of old ones. Number of values should be equal to the number specified as parameter.

Example

<script>

var arr = [1,2,3,4,5];
document.write("original: " + arr); //1,2,3,4,5
document.write("<br />");

var new_arr = arr.splice(3,2,"four","five");
document.write("Removed: " + new_arr); //4,5
document.write("<br />");

document.write("new: " + arr); //1,2,3,four,five

/*********output************
original: 1,2,3,4,5
Removed: 4,5
new: 1,2,3,four,five
***************************/

</script>

Reversing the elements of Array

reverse() method is used to reverse the elements of an array.

Syntax

array_name.reverse()

Example

<script>

var arr = [1,2,3,"four"];
arr.reverse(); //four,3,2,1
document.write(arr);

</script>

Sorting in JavaScript

sort() method is used to sort the elements of an array in ascending order and returns the sorted array.

Syntax

array_name.sort([compareFunction])

An optional parameter compareFunction can be passed inside sort() method. In case optional compareFunction is not passed then elements of the array will be converted into string form and then dictionary sort will be performed.

For example, 1,2,10 will be sorted as 1,10,2. b,a,A will be sorted as A,a,b.

Example

<script>

/*****Dictionary Sort*******/

var arr = [1,2,10];
arr.sort(); //1,10,2
document.write(arr);
document.write("<br />");

arr = ['b','a','A'];
arr.sort(); //A,a,b
document.write(arr);

</script>

If compareFunction is supplied then sort() method will pass successive pair of array elements as parameters to compareFunction according to which compareFunction will return an integer value. Suppose a and b are two elements that are passed to compareFunction.

  • If 'a' will be greater than 'b' then compareFunction will return positive value which means that 'a' should be placed at higher index than 'b'.
  • If 'a' will be smaller than 'b' then compareFunction will return negative value which means that 'a' shouldl be placed at lower index than 'b'.
  • If 'a' equals to 'b' then compareFunction will return 0 which means do not change any positions.

Example

<script>

//lets define our compareFunction
function sortNumbers(a,b)
{
	return a-b;
}

var arr = [5,3,2,4,1];
document.write("original: " + arr);
document.write("<br />");

arr.sort(sortNumbers); //sortNumbers is our compareFunction
document.write("sorted: " + arr);

</script>

Getting array as String

join() method

join method combines all the elements of an array and returns it as a string. The elements are separated by a specified separator which is passed as a parameter to join method. If no parameter is supplied then join will separate each element of an array by ','.

Syntax

array_name.join([separator])

Example

<script>

var arr = [1,2,3,4,5];
str = arr.join(' and ');
document.write(str);

</script>

toString() method

toString method returns string representation of an array and its elements.

JavaScript automatically calls this method whenever an array is to be represented as a text value.

Syntax

array_name.toString()

Example

<script>

var arr = [1,2,3,4,5];
str = arr.toString();
document.write(str);

</script>

Filtering array elements in JavaScript

filter() method

filter() method is used to filter the elements of an array. filter() method accepts a callback function as parameter to which all the elements of array are passed one by one.

Syntax

array.filter(function(arr){
	//you filtering code
})

Example

<script>

var array = [1,2,3,4,5];
var filter = array.filter(function(arr){ if(arr!=3) return; });
document.write(filter);
//1,2,4,5


//another example
var numbers = [1,2,3,4,5,6,7,8,9,10];
var filtered = numbers.filter(function evenNumbers(number)
{
	if(number%2===0)
	{
		return number;
	}
});
console.log(filtered);
// [2,4,6,8,10]

</script>

Summary of Array Methods in JavaScript

Method Description
array.push(values) returns new length after adding values to the end of an array
array.pop() returns last element after deleting it from an array
array.unshift(values) returns new length after adding values to the start of an array
array.shift() returns first element after deleting it from an array
array.slice(start,[end]) returns the elements between the index passed as parameter. end position index element is excluded
array.splice(pos,num,vals) returns the replaced elements specified by the index parameter after replacing it with the new values
array.reverse() returns an array in reverse order
array.sort([compareFun]) returns an array sorted in ascending order. If no parameter is given array is sorted as dictionary sort
array.join([separator]) returns the elements of an array as a string joining them with the given separator.
array.toString() returns the elements of an array as a string
array.filter(callback function(arg)) returns the filtered array after passing elements to callback function
<< Loop Control Statements Working with Numbers >>