You are here: Reference > JavaScript > core > objects > Array

Array object

Browser support:
The Array object lets you store a group of data in a variable.
The elements in a JavaScript array can have different data types, and they can be accessed by indexing.

Elements of an array can also be arrays. In that case, the array is a multi-dimensional array. The elements within a multi-dimensional array are accessed using more than one index: one for each dimension. Two dimensional arrays can be visualized as a multicolumn table, and a multi-dimensional (one with more than two dimensions) as a tree.

JavaScript allows using associative arrays, too. In this type of arrays, each stored value is associated with a unique key, which can be used as an index. The unique keys are string types. In JavaScript, every object can behave like an associative array.
How to use associative arrays?
You can set a member of an arbitrary object in two ways:
  • object.member = value
  • object["member"] = value
Similarly, you can use the following forms, too:
  • value = object.member
  • value = object["member"]
  • object.member (param1, param2, ...)
  • object["member"] (param1, param2, ...)
In the 'Array operations' section below, you can find examples that illustrate the use of associative arrays.

Syntax:

Creating an empty Array object:
var arr = new Array ();
Creating an Array object with initial length:
var arr = new Array ([length]);
  • If length is not specified, creates an empty array.
  • The value of the length parameter must be a non-negative integer.
  • If the type of the length parameter is not a number, then creates a one-element array containing the specified value. See the 'Creates a new Array object with initial elements' section below.
  • If the type of the length parameter is a number, then it must be a non-negative integer, else it causes error.
  • The elements are undefined in an array that is created with initial length.
Creating an Array object with initial elements:
var arr = new Array (element1, element2, ..., elementN);
The newly created array contains the specified elements.
  • If no elements are specified, creates an empty array.
  • If only one element is specified and it is a number, then it defines the length of the array! See the 'Creates a new Array object with initial length' section above.
Creating an Array object with an array literal:
var arr = [element1, element2, ..., elementN];
The newly created array contains the specified elements. If no elements are specified, creates an empty array.

Array operations

Creating a simple array:
    // In both cases the arr variable is an array that has three element: A, B, C
var arr = new Array ("A", "B", "C");
    // or
var arr = ["A", "B", "C"];

    // you can access the elements of the array by zero-based indices
var firstItem = arr[0];     // "A"
var thirdItem = arr[2];     // "C"

    // you can get the length of the array by the length property
var len = arr.length;       // 3
Did you find this example helpful? yes no
Creating a multidimensional array (array of arrays):
var arr1 = new Array ("A", "B", "C");
var arr2 = new Array (1, 2, 3);
var multiArr = new Array (arr1, arr2);
    // or
var multiArr = [arr1, arr2];
    // or
var multiArr = [["A", "B", "C"], [1, 2, 3]];

    // you can access the elements of the array by zero-based indices
var firstRow = multiArr[0];     // same as arr1
var secondRowFirstCell = multiArr[1][0]; // 1
Did you find this example helpful? yes no
The multiArr variable is an array that has two elements, the first element is an array (A,B,C), and the second element is another array with elements (1,2,3).
Multidimensional arrays are useful for example if you want to store the full contents of a table element in an array.
Iterating through a simple array:
var arr = ["A", "B", "C"];

    // display the elements of the array (ABC)
for (var i = 0; i < arr.length; i++) {
    document.write (arr[i]);
}

    // iterating with the for in statement, i will be 0, 1, 2. 
    // The output will be ABC
for (var i in arr) {
    document.write (arr[i]);
}
Did you find this example helpful? yes no
Adding elements to an array:
    // First we must create an array:
var arr = [];
    // Add elements at the first position:
arr[0] = "A";
    // Add elements at the second position:
arr[1] = "B";
    // Adding an element to the end of the array:
arr.push ("C");
    // Now the arr variable is an array that have three elements: A,B,C.
Did you find this example helpful? yes no
Joining two array objects into a new one:
var arr1 = ["A", "B", "C"];
var arr2 = [1, 2, 3];
    // Concat the arrays:
var newArr = arr1.concat (arr2);
    // Now the newArr variable is an array that has six elements: A,B,C,1,2,3.
Did you find this example helpful? yes no
Deleting elements from a simple array:
var arr = ["A", "B", "C"];
document.write (arr);   // output: A,B,C

arr.splice (1, 1);
document.write ("<br />");
document.write (arr);   // output: A,C
Did you find this example helpful? yes no
Creating an associative array:
var arr = {};
    // You can add elements to an associative array in two different ways:
arr["name"] = "John";
arr["location"] = "Utah";
    // second way
arr.age = 13;

    // you can access the elements of this array by string indices
var loc = arr["location"];  // "Utah"
    // or like a member
var loc = arr.location;     // "Utah"

    // you cannot get the length of the array via the length property, 
    // it contains an invalid value
var len = arr.length;       // len will be 0
Did you find this example helpful? yes no
Iterating through an associative array:
var arr = {};
arr["name"] = "John";
arr["location"] = "Utah";
arr["age"] = 13;

    // iterating with the for in statement, i will be 'name', 'location', 'age'. 
    // The output will be JohnUtah13
for (var i in arr) {
    document.write (arr[i]);
}
Did you find this example helpful? yes no
Deleting elements from an associative array:
var arr = {};
arr["name"] = "John";
arr["location"] = "Utah";
arr["age"] = 13;
    // display the initial contents of the array, output: JohnUtah13
for (var i in arr) {
    document.write (arr[i]);
}

delete arr.location;    // delete the location property from the array
document.write ("<br />");
    // display the current contents of the array, output: John13
for (var i in arr) {
    document.write (arr[i]);
}
Did you find this example helpful? yes no

Members:

The Array object inherits from the Array.prototype and Function.prototype objects. The following lists only contain the members of the Array and Array.prototype objects.

Properties:

Property Support Description
index*
Works only for regular expression arrays returned by the exec method. Returns an integer value that indicates the zero-based starting position of the match in the original string.
input*
Returns the original string, for regular expression arrays returned by the exec method.
length*
Returns the number of elements in the current array.
prototype
Returns a reference to the Array.prototype object. The Array.prototype object allows adding properties and methods to the Array object that can be used with instances of the Array object, like any predefined property or method. The prototype property is static, it cannot be accessed from an instance of the Array object, only Array.prototype is allowed.

(*) - The property is inherited from the Array.prototype.

Methods:

Method Support Description
[index]
Returns the element at the specified position.
concat ([array1 [,arrayN]...])*
Joins the current array with the specified arrays and returns the combined array.
every (function [, thisObject])*
9
Checks whether the given function returns true for all elements in the array, and if so, it returns true, else it returns false.
filter (function [, thisObject])*
9
Executes the given function for each element in the array and retrieves an array filled with elements for which the given function returns true.
forEach (function [, thisObject])*
9
Executes the given function for each element in the array.
indexOf (elemToSearch [, fromIndex])*
9
Tries to find the given elemToSearch element within the array and returns the index of the first match or -1.
join ([separator])*
Returns a string that contains the value of the elements in the array separated by the given separator.
lastIndexOf (elemToSearch [, startIndex])*
9
Tries to find the given elemToSearch element backwards within the array and returns the index of the first match or -1.
map (function [, thisObject])*
9
Executes the given function for each element in the array and returns a new array filled with the return values.
pop ( )*
Removes the last element from the array and returns the removed element.
push ([newElement1 [,newElementN]...])*
Adds one or more elements to the end of the array and returns the new length of the array.
reverse ( )*
Returns a new array with the elements of the original array but in reverse order.
shift ( )*
Removes the first element from the array and returns the removed element.
slice (start, [end])*
Returns an array filled with the elements of the current array from the start position to end.
some (function [, thisObject])*
9
Checks whether the given function returns true for at least one element in the array, and if so, it returns true, else it returns false.
sort ([compareFunction])*
If the compareFunction is not defined, sorts the elements of the array in lexicographical order, else the order of the elements is based on the compareFunction method.
splice (start, howmany [, newElement1 [,newElementN]...])*
Inserts and removes elements from the array.
toSource ( )*
Returns a string representing the source code of the current array.
toString ( )*
Returns a string that contains the value of the elements in the array separated by commas. If you want to concatenate the values with a separator other than comma, use the join method.
unshift (newElement1 [, newElement2 ... [, newElementN]])*
Inserts one or more elements at the beginning of the array.

(*) - The method is inherited from the Array.prototype.

Properties

index

Works only for regular expression arrays returned by the exec method. Returns an integer value that indicates the zero-based start position of the match in the original string.
var str = "The apple is a tree and it is a pomaceous fruit.";
var rgExp = /\w+/g;    // The regular expression
var match;
while ((match = rgExp.exec(str)) != null) {
    document.write (match.index + "-" + rgExp.lastIndex + "\t" + match);
    document.write ("<br />");
}
Did you find this example helpful? yes no
Output:
Displays the starting and end positions of the words in the str (string) variable.
0-3 The
4-9 apple
10-12 is
13-14 a
15-19 tree
20-23 and
24-27 its
28-37 pomaceous
38-43 fruit

input

Returns the original string, for regular expression arrays returned by the exec method.
var str = "The apple is a tree and its pomaceous fruit.";
var rgExp = /\w+/g;    // The regular expression
var match = rgExp.exec(str);
document.write (match.input);   // display: "The apple is a tree and its pomaceous fruit."
Did you find this example helpful? yes no

length

Returns the number of elements in the current array.
var arr = ["A", "B", "C"];
document.write (arr.length); // display: 3
Did you find this example helpful? yes no

prototype

Allows adding properties and methods to the Array object, which can be used like any predefined property or method listed here.
<head>
    <script type="text/javascript"> 
        Array.prototype.AddCherry = function () {
            return this.push ("cherry");    // call Array.push method
        }
    </script>
</head>
<body>
    <script type="text/javascript">
        var arr = ["apple", "peach"];
        arr.AddCherry ();
        document.write (arr);   // display: apple,peach,cherry
    </script>               
</body>
Did you find this example helpful? yes no

Methods

[index]

Returns the element at the specified position.
index Required. Zero-based integer that specifies the index of the character.
Return value: Returns the element at the specified position. If the position is not valid, returns undefined.
var arr = [10, -2, 20];
    // output -2
document.write (arr[1]);
Did you find this example helpful? yes no

concat ([array1 [,arrayN]...])

Joins the current array with the specified arrays and returns the combined array. The current array is not changed by the concat method.
[array1 [,arrayN]...] Specifies one or more arrays to concatenate to the current array.
Return value: Returns the newly created array.
var arr1 = ["A", "B", "C"];
var arr2 = [1, 2, 3];
    // Concat the arrays:
var newArr = arr1.concat (arr2); // Now newArr contains six elements: A,B,C,1,2,3
document.write (newArr);    // display: A,B,C,1,2,3
Did you find this example helpful? yes no

every (function [, thisObject])

9
Checks whether the given function returns true for all elements in the array, and if so, it returns true, else it returns false.
function Required. Specifies the callback function that needs to be called for the elements of the array.
thisObject Optional. In the callback function, this refers to the window object by default. If the thisObject parameter is specified, this will refer to its value.
Return value: Returns the calculated boolean value.
true The given function returns true for all elements in the current array.
false The given function returns false for one or more elements in the current array.
var arr = [3, 6, 2, 8];
function CheckIfLowerThan (elem) {
    return (elem < 10);
}
    // displays 'true', because all elements in the array are lower than 10.
if (arr.every) {
    document.write (arr.every (CheckIfLowerThan));
} else {
    alert ("Your browser does not support every method!");
}
Did you find this example helpful? yes no

filter (function [, thisObject])

9
Executes the given function for each element in the array and retrieves an array filled with elements for which the given function returns true.
function Required. Specifies the callback function that needs to be called for the elements of the array.
thisObject Optional. In the callback function, this refers to the window object by default. If the thisObject parameter is specified, this will refer to its value.
Return value: Returns the newly created array.
var arr = [3, 16, 2, 18];
function CheckIfLowerThan (elem) {
    return (elem < 10);
}
if (arr.filter) {
    var newArr = arr.filter (CheckIfLowerThan);  // Now newArr contains two elements: 3,2
    document.write (newArr);    // display: 3,2
} else {
    alert ("Your browser does not support filter method!");
}
Did you find this example helpful? yes no

forEach (function [, thisObject])

9
Executes the given function for each element in the array.
function Required. Specifies the callback function that needs to be called for the elements of the array.
thisObject Optional. In the callback function, this refers to the window object by default. If the thisObject parameter is specified, this will refer to its value.
Return value: This function does not return a value.
var arr = [3, 16, 2, 18];
var newArr = [];

function AddToNewArray (elem) {
    newArr.push (elem + 5);
}
if (arr.forEach) {
    arr.forEach (AddToNewArray);
        // newArr contains: (8, 21, 7, 23) , 
        // because the 'AddToNewArray' function increments 
        // all elements in the original array by 5 and 
        // adds them to the 'newArr' array.
    document.write (newArr);    // display: 8,21,7,23
} else {
    alert ("Your browser does not support forEach method!");
}
Did you find this example helpful? yes no

indexOf (elemToSearch [, fromIndex])

9
Tries to find the given elemToSearch element within the array and returns the index of the first match or -1. An element of the array match the elemToSearch element if their values and types are equal (strict equal operator ===).
elemToSearch Required. Specifies the string to search for.
fromIndex Optional. The zero-based position where the search is started. If not specified, the starting position is zero.
Return value: Returns the index of the first match or -1 if no match is found.
var arr = ["A", "B", "C"];
if (arr.indexOf) {
    var pos = arr.indexOf ("B");
        // The value of 'pos' is 1 , 
        // because the array's second element is 'B' 
        // (1 because the first element's index is 0).
    document.write (pos);   // display: 1
} else {
    alert ("Your browser does not support indexOf method!");
}
Did you find this example helpful? yes no

join ([separator])

Returns a string that contains the value of the elements in the array separated by the given separator. The join method converts the values to string first then concatenates them using the separator.
separator Optional. Specifies the separator that divides the array elements in the returned string. The default is the comma character.
Return value: Returns the string created from the elements of the array.
var arr = ["A", "B", "C"];
var str = arr.join (":"); // A:B:C
document.write (str);   // display: A:B:C
Did you find this example helpful? yes no

lastIndexOf (elemToSearch [, fromIndex])

9
Tries to find the given elemToSearch element backwards within the array and returns the index of the first match or -1. An element of the array matches the elemToSearch element if their values and types are equal (strict equal operator ===).
elemToSearch Required. Specifies the string to search for.
fromIndex Optional. The zero-based position where the backward search is started. If not specified, the starting position is the last position in the array.
Return value: Returns the index of the first match or -1 if no match is found.
var arr = ["A", "B", "C", "B"];
if (arr.lastIndexOf) {
    var pos = arr.lastIndexOf ("B");
        // The value of 'pos' is 3 , 
        // because the array's fourth element is 'B' 
        // (3 because the first element's index is 0).
    document.write (pos);   // display: 3
} else {
    alert ("Your browser does not support lastIndexOf method!");
}
Did you find this example helpful? yes no

map (function [, thisObject])

9
Executes the given function for each element in the array and returns a new array filled with the return values.
function Required. Specifies the callback function that needs to be called for the elements of the array.
thisObject Optional. In the callback function, this refers to the window object by default. If the thisObject parameter is specified, this will refer to its value.
Return value: Returns the newly created array.
var arr = [3, 16, 2, 18];

function Increase (elem) {
    return (elem + 5);
}
if (arr.map) {
    var newArr = arr.map (Increase);
        // The newArr contains: (8, 21, 7, 23) , 
        // because the Increase function increments 
        // all elements in the original array by 5.
    document.write (newArr);    // display: 8,21,7,23
} else {
    alert ("Your browser does not support map method!");
}
Did you find this example helpful? yes no

pop ()

Removes the last element from the array and returns the removed element.
Return value: Returns the removed element or undefined if the array is empty.
var arr = ["A", "B", "C"];
document.write (arr.pop ()); // displays C
document.write ("<br />");
document.write (arr);   // display: A,B
Did you find this example helpful? yes no

push ([newElement1 [,newElementN]...])

Adds one or more elements to the end of the array and returns the new length of the array.
[newElement1 [,newElementN]...] One or more elements to add.
Return value: Returns the new length of the array.
var arr = ["A", "B", "C"];
arr.push ("D", "E");    // The 'arr' contains: ("A", "B", "C", "D", "E")
document.write (arr);   // display: A,B,C,D,E
Did you find this example helpful? yes no

reverse ()

Returns a new array filled with the elements of the original array but in reverse order.
Return value: Returns the newly created array.
var arr = ["A", "B", "C"];
var newArr = arr.reverse ();    // The 'newArr' contains: ("C", "B", "A")
document.write (newArr);    // display: C,B,A
Did you find this example helpful? yes no

shift ()

Removes the first element from the array and returns the removed element.
Return value: Returns the removed element or undefined if the array is empty.
var arr = ["A", "B", "C"];
arr.shift ();   // The 'newArr' contains: ("B", "C")
document.write (arr);   // display: B,C
Did you find this example helpful? yes no

slice (start, [end])

Returns an array, filled with the elements of the current array from the position start to end.
start Required. The index of the first element to insert into the returned array.
end Optional. The index of the element after the last element to insert into the returned array. If not specified, all elements after the start index will be returned. Negative values are allowed, the -1 value means the last index in the array, the -2 value means the (last-1) index, ...
Return value: Returns the newly created array.
var arr = ["A", "B", "C"];
var subArr = arr.slice (1, 2);
document.write (subArr);    // output: B
document.write ("<br />");

subArr = arr.slice (1, 3);
document.write (subArr);    // output: BC
document.write ("<br />");

subArr = arr.slice (0, -1);
document.write (subArr);    // output: AB
document.write ("<br />");

subArr = arr.slice (1);
document.write (subArr);    // output: BC
document.write ("<br />");

subArr = arr.slice (1, 1);  // empty array
Did you find this example helpful? yes no

some (function [, thisObject])

9
Checks whether the given function returns true for at least one element in the array, and if so, it returns true, else it returns false.
function Required. Specifies the callback function that needs to be called for the elements of the array.
thisObject Optional. Inside the callback function, this refers to the window object by default. If the thisObject parameter is specified, this will refer to its value.
Return value: Returns the calculated boolean value.
var arr = [3, 16, 2, 8];
function CheckIfLowerThan (elem) {
    return (elem < 10);
}
    // displays 'true', because 2, 3 are lower than 10.
if (arr.some) {
    document.write (arr.some (CheckIfLowerThan));
} else {
    alert ("Your browser does not support some method!");
}
Did you find this example helpful? yes no

sort ([compareFunction])

If the compareFunction is not defined, sorts the elements of the array in lexicographical order, else the order of the elements is based on the compareFunction method.
compareFunction Optional. Function that can compare two arbitrary elements from the array.
The compareFunction defines an ordering for any two elements in the array. It gets two parameters (a and b) from the sort method, where a and b are arbitrary elements from the array.
If a is less than b by the ordering criterion, the compareFunction must return a value less than 0.
If a is greater than b by the ordering criterion, the compareFunction must return a value greater than 0.
If a and b are equal, it must return 0.
The sort method uses this returned value for sorting the elements.
Return value: Returns the sorted array.
1. Example: This example uses the sort method without a compareFunction parameter.
var arr = ["B", "A", "b", "a", 3, 20];
document.write ("Original order: " + arr + "<br />");   // output: B,A,b,a,3,20
arr.sort ();
document.write ("Sorted order: " + arr);    // output: 20,3,A,B,a,b
Did you find this example helpful? yes no
2. Example: This example uses the sort method with a compareFunction parameter.
var arr = [210, 7, 132, 20];

function compare (a, b) {
            // display information about the elements to compare
    document.write ("Comparing elements: " + a + ", " + b + "<br />");
    
    if (a < b)
        return -1;
    if (a > b)
        return 1;
    return 0;
}

document.write ("Original order: " + arr + "<br />");   // output: 210,7,132,20
arr.sort (compare);
document.write ("Sorted order: " + arr);    // output: 7,20,132,210
Did you find this example helpful? yes no

splice (start, howmany [, newElement1 [,newElementN]...])

Inserts and removes elements from the array.
start Required. The starting index where deleting and insertion starts.
howmany Required. The number of elements to remove.
newElement1 [,newElementN] Optional. The new elements to insert at the position specified by the start parameter.
Return value: Returns an array filled with the removed elements.
    // removes some elements from an array
var arr = ["A", "B", "C", "Z"];
arr.splice (1, 2);
document.write (arr);   // output: A,Z
document.write ("<br />");

    // inserts some elements into an array
arr = ["A", "B", "C", "Z"];
arr.splice (1, 0, "D", "E");
document.write (arr);   // output: A,D,E,B,C,Z
document.write ("<br />");

    // removes and inserts some elements from an array
arr = ["A", "B", "C", "Z"];
arr.splice (1, 2, "D", "E");
document.write (arr);   // output: A,D,E,Z
Did you find this example helpful? yes no

toSource ()

Returns a string representing the source code of the current array.
Return value: Returns a string representing the source code.
var arr = new Array("A", "B", "C");
var source = arr.toSource();
document.write (source);    // display: ["A", "B", "C"]
Did you find this example helpful? yes no

toString ()

Returns a string that contains the value of the elements in the array separated by commas.
When an array needs to be converted to a string, the JavaScript interpreter automatically calls its toString method.

If you want to concatenate the values with a separator other than comma, use the join method.
Return value: Returns a string representing the value.
var arr = ["A", "B", "C"];
var str = arr.toString ();
document.write (str);   // display: A,B,C
Did you find this example helpful? yes no

unshift (newElement1 [, newElement2 ... [, newElementN]])

Inserts one or more elements at the beginning of the array.
newElement1 [, newElement2 ... [, newElementN]] Required. One or more elements to add.
Return value: Returns the new length of the array.
var arr = ["A", "B", "C"];
arr.unshift (1, 2, 3);
document.write (arr);   // output: 1,2,3,A,B,C
Did you find this example helpful? yes no

External links:

User Contributed Comments

Post Content

Post Content