JavaScript Array

By:    Updated: January 24,2017

The Array type is probably the most used in JavaScript. It can hold any type of data in each slot. It also allows stack-like and queue behavior.

JavaScript Array Creation

It's possible to create an array that has a string in the first position, a number in the second, an object in the third, and so on.Javascript arrays are also dynamically sized, automatically growing to accommodate any data that is added to them.

<script type="text/javascript">
//Using new Array constructor
var books1 = new Array(); //an empty array

//new Array(length) which length is the number of items
var books2 = new Array(5);

//Creates an array with 6 values
var books3 = new Array("linux", "nginx", "mysql", "php", "javascript", 28);

//Using array literal notation which without new Array
var books4 = ["linux", "nginx", "mysql", "php", "javascript", 28];

var books5 = []; //an empty array
</script>

The number of items in an array is stored in the length property, which starts from 0.The position (or index) of the last item of an array is length-1.

<script type="text/javascript">
var books = ["linux", "nginx", "mysql", "php", "javascript", 28];

var length = books.length;
var first_item = books[0]; //linux
var last_item = books[length-1]; //28

books[5] = "redis"; //The old item of position is "28", now changed to "redis"

books[7] = "mongodb"; //The 8th item isn't exist, so it will be added to end of an array

//The array length is automatically expanded to (position+1) if position>=length
var new_length = books.length; //8

books.length = 10;
alert(books[8]); //It is undefined even though the array expanded to hold 10 items.

books.length = 4;
alert(books[5]);//It is undefined when its position >= length (In other words, it is removed)
</script>

String Representation

There are some approaches to get the string representation of the array.

<script type="text/javascript">
var books = ["linux", "nginx", "mysql", "php", "javascript", 28];

alert(books.toString());
alert(books.valueOf());
alert(books.join(","));
alert(books);
</script>

Stack Methods

An array object can act just like a stack, which is one of a group of data structures that restrict the insertion and removal of items. A stack is referred to as a last-in-first-out (LIFO) structure, meaning that the most recently added item(added to the end of the array) is the first one removed(removed from the end of the array).

<script type="text/javascript">
var books = ["linux", "nginx"];

//The push() method accepts any number of arguments and adds them to the end of the array,
//returning the array's new length.
var new_length = books.push("mysql", "php");

alert(books); //linux,nginx,mysql,php
alert(new_length); //4

//The pop() method gets the last item of the array and removed it
var last_item = books.pop(); //php
alert(books); //linux,nginx,mysql
alert(books.length); //3
</script>

Queue Methods

Queues restrict access in a first-in-first-out(FIFO) data structure. A queue adds items to the end of a list and retrieves items from the front of the list.

<script type="text/javascript">
var books = ["linux", "nginx"];

//add 2 items to the end of an array
books.push("mysql", "php");

alert(books); //linux,nginx,mysql,php

//The shift() method gets the first item of the array and removed it
var first_item = books.shift(); //linux
alert(books); //nginx,mysql,php
alert(books.length); //3

//The unshift() method accepts any number of arguments and adds them to the front of the array,
//returning the array's new length.
var new_length = books.unshift("redis", "mongodb");
alert(books); //redis,mongodb,nginx,mysql,php
alert(new_length); //5
</script>

Reordering Methods

Two methods deal directly with the reordering of items already in the array: reverse() and sort(). The reverse() method simply reverses the order of items in an array.The sort() method puts the items in ascending order unless you pass in a comparison function indicates that how the items should be sorted.

 

A comparison function accepts two arguments and returns a negative number if the first argument should come before the second, a zero if the arguments are equal, or a positive number if the first argument should come after the second.

<script type="text/javascript">
var ranking = [1,10,7,6,17,13];

//reverse() simply reverses
ranking.reverse();
alert(ranking); //13,17,6,7,10,1

//sort
function callbackCompareAscending(value1, value2)
{
	//method1
	if(value1 < value2)
	{
		//ascending: smaller come before, so we need to return the negative number
		return -1; 
	}
	else if(value1 > value2)
	{
		return 1;
	}
	else
	{
		return 0
	}

   //method2
   //return (value1 - value2);
}
function callbackCompareDescending(value1, value2)
{
	//method1
	if(value1 < value2)
	{
		//descending: smaller come after, so we need to return the positive number
		return 1; 
	}
	else if(value1 > value2)
	{
		return -1;
	}
	else
	{
		return 0
	}

   //method2
   //return (value2 - value1);
}

ranking.sort(callbackCompareAscending);
alert(ranking); //1,6,7,10,13,17

ranking.sort(callbackCompareDescending);
alert(ranking); //17,13,10,7,6,1
</script>

Manipulation Methods

There are various ways to work with the items already contained in an array.

<script type="text/javascript">
var books1 = ["linux"];

//concat()
//1. If no arguments are passed in, concat() simply clones the array and returns it.
//2. If one or more arrays are passed in, concat() appends each item in these arrays to the end of the result. 
//3. If the values are not arrays, they are simply appended to the end of the resulting array.
var books2 = books1.concat("nginx", ["redis" , "mongodb"], "memcached");
alert(books2); //linux,nginx,redis,mongodb,memcached


//slice(start_position, end_position = length)
//1. Array position start from 0.
//2. Not including the item in the end position.
//3. Old array will not be destroyed.
//4. If either the start or end position of slice() is a negative number, you can use (array.length + position) to
//convert to positive number. If the end position is smaller than the start after converting, 
//then an empty array is returned.

//It only passes one argument(start_position), so it will return all items between that position and the end of the array
var books3 = books2.slice(3);
alert(books2); //It still remains linux,nginx,redis,mongodb,memcached
alert(books3); //mongodb,memcached

var books4 = books2.slice(2, 4);
alert(books4); //redis,mongodb

var books5 = books2.slice(-2, -1); //the same as (3, 4)
alert(books5); //mongodb


//splice(start_position, remove_numbers, insert_item_1, insert_item_2, ...)
//1. By specifying just two arguments: delete the numbers (remove_numbers) of items which start from the position(start_position),
//then return the delete items.
//2. By specifying more than two arguments: delete the numbers of items which start from the position, then insert items start from 3rd arguments respectively and return the delete items at last.
var books6 = books2.splice(2, 2);
alert(books2); //linux,nginx,memcached
alert(books6); //redis,mongodb

var books7 = books2.splice(1, 1, 28, "flasle");
alert(books2); //linux,28,flasle,memcached
alert(books7); //nginx
</script>

Location Methods

There are two item location methods to array instances: indexOf() and lastIndexOf() in Javascript. Each of them returns the position of the item in the array or –1 if the item isn’t in the array. A string can be seen as a array which join with "".Each character of string is one item of the array.

<script type="text/javascript">
var ranking = [1,10,7,6,17,13,10,99,2,28];

//indexOf(search_item, search_start_position_from_front); //search from front to end
//if only specifying one argument, search from position 0
alert(ranking.indexOf(10)); //1
alert(ranking.indexOf(10, 3)); //6

//lastIndexOf(search_item, search_start_position_from_front); //search from end to front
//if only specifying one argument, search from position length-1
alert(ranking.lastIndexOf(10)); //6
alert(ranking.lastIndexOf(10, 5)); //1
alert(ranking.lastIndexOf(10, 7)); //6

var findme = "hello,i am here."; //string
alert(findme.length); //16
alert(findme.indexOf("i")); //6
</script>

Iterative Methods

There are five iterative methods for arrays in Javascript. Each of the methods accepts two arguments: a function to run on each item and an optional scope object in which to run the function (affecting the value of this).

<script type="text/javascript">
var ranking = [1,10,7,6,17,13,10,99,2,28];

//every(): Runs the given function on every item in the array.
//It returns true if the function returns true for every item.
var ranking_every = ranking.every(function(item, index, array)
{
	return (item > 5);
});
alert(ranking_every); //false, because 1 and 2 less than 5


//some(): Runs the given function on every item in the array
//It returns true if the function returns true for any one item.
var ranking_some = ranking.some(function(item, index, array)
{
	return (item > 5);
});
alert(ranking_some); //true, because one of the items is greater than 5 at least 


//filter(): Runs the given function on every item in the array.
//It returns an array of all items for which the function returns true.
var ranking_filter = ranking.filter(function(item, index, array)
{
	return (item > 5);
});
alert(ranking_filter); //10,7,6,17,13,10,99,28


//forEach(): Runs the given function on every item in the array.
//It doesn't return value.
var ranking_foreach = ranking.forEach(function(item, index, array)
{
	if(item > 5)
	{
		alert("item:" + item + ", index:" + index);
	}
});


//map(): Runs the given function on every item in the array.
//It returns the result of each function call in an array.
var ranking_map = ranking.map(function(item, index, array)
{
	return item;
});
alert(ranking_map); //1,10,7,6,17,13,10,99,2,28
</script>
More in Development Center
New on Valinv
Related Articles
Sponsored Links