An array is an ordered list of values. In various languages an array is called things like vector, list, or sequence. Contrast the array concept with the JS object: A collection of name and value pairs, which, in other languages, is called things like record, struct, dictionary, hash table, keyed list, or associative array

Arrays use a lot of literal square brackets []. I am not going to mark them in bold on this page to distinguish them from optional items.

Basic Usage

The index of JavaScript arrays are zero-based, i.e. from 0 to length-1. EG: To reference the first (or 0th) element in the myArray object, use myArray[0]; to reference the fifth (or 4th), use myArray[4].

var myA = new Array(); //Default array length is 0
var myB = []; //Preferred because possible confusion whether parameter is size of array or element.
var myObj = new Array(arrayLength) // Max length is (2^32)-1, i.e. 4,294,967,295
var myA = new Array(3); // This array has a length of 3
var x = myA[0]; // x is now null because the 0th element is not initialized
myA[5] = 9; // Writing into an out of range index changes the length

Different ways to fill an array:

var myObj = new Array([value0[, value1[, ..., valueN]]])
var myA = new Array(6, new Date(), "hi"); // Arrays may have different data types
myObj[0]=value0; [ ... myObj[N]=valueN; ]
myA[0]=6; myA[1]=new Date(); myA="hi";
var myObj = [value0[, value1[, ..., valueN]]] // This syntax is not like c or Java
var myA = [6, new Date(), "hi"]; // An array literal

One of the most common things done to an array is looping through it.

var i = 0, myA = [0, 1, 1, 2, 3, 5, 8, 13];
// Left to right
for (i = 0; i < myA.length; i++) {
    document.write("myA[" + i + "]: " + myA[i] + "<br>");
}
// Right to left
for (i = myA.length - 1; i >= 0; --i) {
    document.write("myA[" + i + "]: " + myA[i] + "<br>");
}

Multi-dimensional arrays are possible. Start with 2D with an array of arrays. EG: This make a 4x3 array whose elements would be referenced as myA[i][j].

var myA = new Array(4);
for (i = 0; i < 4; i++) {
    a[i] = new Array(3);
}

Since an array is an object, you can actually add properties and methods that are not referenced by number. Arrays with elements referenced by key names (i.e. by property names) are called associative arrays. In which such a case it is actually an object (a container of things referenced by name).

var myObjectVariable = {key0:value0[, key1:value1[, ..., keyN:valueN]]}
var myA = {make:"Honda", model:"Accord", year:1998};
var myA = new Array();
myA['make'] = "Honda";
myA['model'] = "Accord";
myA['year'] = 1998;

I'm just going to scribble a little here about a topic very related to arrays: last-in-first-out (LIFO) and first-in-first out (FIFO).

  • Last-in-first-out (LIFO) are commonly called stacks. A common visualization is usually a spring loaded stack of plates. The easiest place to add a plate is at the top. The easiest place to remove a plate is also at the top. With LIFO you "push" at the top, and "pop" out at the top.
  • First-in-first out (FIFO) are commonly called queues, pipes, or first-come-first-served (FCFS). A common visualization is a print queue. You add print jobs to the queue and you do them in order from oldest to newest. With FIFO you "push" at the top, and "pop" out at the bottom.

Here is a summary of the related JavaScript array methods:

  • .pop() removes the rightmost element, and returns it.
  • .push() adds elements at the right, and returns the new length.
  • .shift() removes the leftmost element, and returns it.
  • .unshift() adds elements at the left, and returns the new length.

In effect, a JavaScript array is a LIFO stack where the top is at the right (and the spring or bottom is at the left), and thus you .pop() and .push() LIFO-style. If you want to "pop" out FIFO-style (i.e. get out the oldest stuff), then you use .shift().

In general LIFO is more efficient because the indexing stays the same, hence the shorter names of "pop" and "push". In contrast with FIFO each item has to be given a new index number, hence the "shift" and "unshift".

Properties

.index

Implemented: JS 1.2.
For an array created by a regular expression match, the zero-based index of the match in the string. See more at RegExp.

.input

Implemented: JS 1.2.
For an array created by a regular expression match, reflects the original string against which the regular expression was matched. See more at RegExp.

.length

Implemented: JS 1.1; ECMA-262.
Reflects the number of elements in an array. The default array length is 0. Setting the length can truncate the array, but it does not add more elements. Overrides Function.prototype.length.

One technique is to use length to add to an element to the end of an array.

var myA = new Array();
myA[myA.length] = "0th element";
myA[myA.length] = "1st element";

Methods

Most of the methods do not mutate this, i.e. usually a method does not modify the object that called the method.

.concat(value1, value2, ..., valueN)

Implemented: JS 1.2; ECMA-262.
Joins this array with the provided arrays or elements and returns a new array. In Set Theory, this is like a union.

[1,2,3].concat(3,4,[5,6,[7,8]])) // returns [1,2,3,4,5,6,7,8]

.every(testingFunction[, asThisObject])

Implemented in JS 1.6; ECMA-262 not.
Returns true if all elements in the array return true for the testingFunction. The testingFunction has 3 parameters: the current element, the index of the current element, and the array object being traversed. The testingFunction works with the array as it was before the first iteration, i.e. filter does not care or see if the testingFunction modifies the original array. If the 2nd parameter asThisObject is provided, then it will be used as the this in the testingFunction.

function gt2(element, index, array) { return ( element > 2) }
[1,2,3].every(gt2); // returns false
[1,2,3].every(function(e,i,a){return (e>2)}); // returns false

.filter(testingFunction[, asThisObject])

Implemented in JS 1.6; ECMA-262 not.
Creates a new array composed of the elements that return true for the testingFunction. The testingFunction has 3 parameters: the current element, the index of the current element, and the array object being traversed. The testingFunction works with the array as it was before the first iteration, i.e. filter does not care or see if the testingFunction modifies the original array. If the 2nd parameter asThisObject is provided, then it will be used as the this in the testingFunction.

function gt2(element, index, array) { return ( element > 2) }
[1,2,3].filter(gt2); // returns [3]
[1,2,3].filter(function(e,i,a){return (e>2)}); // returns [3]

.forEach(callbackFunction[, asThisObject])

Implemented in JS 1.6; ECMA-262 not.
Executes the callback function once for each element in the array. The callback function has 3 parameters: the current element, the index of the current element, and the array object being traversed. The callback function works with the array as it was before the first iteration, i.e. filter does not care or see if the callback function modifies the original array. If the 2nd parameter is provided, then it will be used as the this in the callback function.

function boo(element, index, array) { alert(element) }
[1,2,3].forEach(boo); // alerts 1,2,3
[1,2,3].forEach(function(e,i,a){ alert(e)}); // alerts 1,2,3

.indexOf(element[, fromIndex])

Implemented: JS 1.6; ECMA-262 not.
Returns the index of the first occurrence of the given value, or -1 if not present. The optional 2nd parameter is the index from which to start looking and defaults to 0 if not provided.

[1,2,3].indexOf(2)   // returns 1
[1,2,3].indexOf(2,2) // returns -1

.join([separator])

Implemented: JS 1.1; ECMA-262.
Joins all elements of an array into a delimited string. If the separator is omitted, then a comma is assumed as the delimiter.

Join is commonly used to compare arrays since objects are compared by reference instead of by value. EGs: These statements are true.

[1,2,3] != [1,2,3];
[1,2,3].join() == "1,2,3";
[1,21,2004].join("/") == "1/21/2004";

If are going to do a lot of string concatenations, then it is more resource efficient to use join():

// Instead of:
var str = 'foo ' + 'bar';
str += str + 'str1 of many concats';

// Do this instead:
var tmp = [];
tmp.push(str);
tmp.push('str2 of many'); // or loop through strings
str = tmp.join('');

The split() method of the String object is used for going the other way since split() returns an array of Strings. EGs:

var myA = "pet,1,dog".split(",");
var myA = "2004-01-21".split("-");
var myA = "name@biz.com".split(/[\.\@]/);
// myA is now an array of ["name","biz","com"]

.lastIndexOf()

Implemented: JS 1.6; ECMA-262 not.
Returns the index of the last occurrence of the given value, or -1 if not present. The optional 2nd parameter is the index from which to start looking backwards and defaults to array length if not provided.

[0,1,2,2,3,4].lastIndexOf(2)   // returns 3
[0,1,2,2,3,4].lastIndexOf(2,1) // returns -1

.map(callbackFunction[, asThisObject])

Implemented in JS 1.6; ECMA-262 not.
Returns an array where a given function has been applied to the original array. The callback function has 3 parameters: the current element, the index of the current element, and the array object being traversed. The callback function works with the array as it was before the first iteration, i.e. filter does not care or see if the callback function modifies the original array. If the 2nd parameter is provided, then it will be used as the this in the callback function.

function dbl(element, index, array) { return ( element * 2) }
[1,2,3].map(dbl); // returns [2,4,6]
[1,2,3].map(function(e,i,a){return (e+3)}); // returns [2,4,6]

.pop()

Implemented: JS 1.2; ECMA-262 Edition 3.
Mutates this.
Removes the last element from an array and returns that element (if there was one to pop).

[1,2,3].pop() // returns 3

.push(element1[, ..., elementN])

Implemented: JS 1.2 returned last element added; JS 1.3 returned new length; ECMA-262 Edition 3.
Mutates this.
Adds one or more elements to the end of this array and returns the new length of the array.

[1,2,3].push(4,4) // returns 5

.reduce(callbackFunction[, initialValue])

Implemented: JS 1.8; ECMA-262 not.
Applies a given function against two elements of an array (left-to-right). The given function has 3 parameters: the previous value, the current element, the index of the current element, and the array object being traversed. If the optional initialValue is provided, then the first iteration of the callback function uses the initial value and the 1st value of the array as previous and current values respectively.

['a','b','c'].reduce(function(p,c,i,a){return p+c})     // a+b=ab, ab+c=abc
['a','b','c'].reduce(function(p,c,i,a){return p+c},'d') // d+a=da, da+b=dab, dab+c=dabc

.reduceRight(callbackFunction[, initialValue])

Implemented: JS 1.8; ECMA-262 not.
Applies a given function against two elements of an array (right-to-left). If the optional initialValue is provided, then the first iteration of the callback function uses the initial value and the 1st value of the array. The given function has 3 parameters: the previous value, the current element, the index of the current element, and the array object being traversed.

['a','b','c'].reduceRight(function(p,c,i,a){return p+c})     // c+b=cb, cb+a=cba
['a','b','c'].reduceRight(function(p,c,i,a){return p+c},'d') // d+c=dc, dc+b=dcb, dcb+a=dcba

.reverse()

Implemented: JS 1.1; ECMA-262.
Mutates this.
Transposes the elements of an array: the first array element becomes the last and the last becomes the first.

[1,2,3].reverse() // returns [3,2,1]

.shift()

Implemented: JS 1.2; ECMA-262 Edition 3.
Mutates this.
Removes the first element from an array and returns the removed element.

[1,2,3].shift() // returns 1

.slice(beginIndex[,endIndex])

Implemented: JS 1.2; ECMA-262 Edition 3.
Extracts a section of an array and returns a new array.

[1,2,3,4].slice(1,3)  // returns [2,3]
[1,2,3,4].slice(1)    // returns [2,3,4]. No endIndex means slice to the end.
[1,2,3,4].slice(1,-1) // returns [2,3]. A negative endIndex means slice to an offset from the end.
[1,2,3,4].slice(-2)   // returns [3,4]. A negative begIndex means slice from the end.

.some(testingFunction[, asThisObject])

Implemented in JS 1.6; ECMA-262 not.
Returns true if any elements in the array return true for the testingFunction. The testingFunction has 3 parameters: the current element, the index of the current element, and the array object being traversed. The testingFunction works with the array as it was before the first iteration, i.e. filter does not care or see if the testingFunction modifies the original array. If the 2nd parameter asThisObject is provided, then it will be used as the this in the testingFunction.

function gt2(element, index, array) { return ( element > 2) }
[1,2,3].some(gt2);                              // returns true
[1,2,3].some(function(e,i,a){return (e>2)}); // returns true

.sort([compareFunction])

Implemented: JS 1.1; JS 1.2 no longer converts undefined to null; ECMA-262.
Mutates this.
Sorts the elements of an array according to a specified function or lexicographically (i.e. dictionary order) by default. Elements that are undefined are put at the end of this array.

[2,11,undefined,3].sort() // returns [11,2,3,undefined]

.splice(startIndex[, howManyToRemove[, elementToAdd][, ..., elementToAddN]])

Implemented: JS 1.2; JS 1.3 returns new array of removed elements; ECMA-262 Edition 3.
Mutates this.
Adds and/or removes elements from an array and returns an array of elements removed or an empty array. startIndex defaults to 0. howManyToRemove defaults to all after startIndex.

var myA = [1,3];
var removed = myA.splice(1,0,2) // removed==[], myA==[1,2,3]
removed = myA.splice(2,1)       // removed==3, myA==[1,2]
removed = myA.splice(0,2,3,2,1) // removed==[1,2], myA==[3,2,1]
removed = myA.splice(0)         // removed==[3,2,1], myA==[]

.unshift(value1[, ..., valueN])

Implemented: JS 1.2; ECMA-262 Edition 3.
Mutates this.
Adds one or more elements to the start of an array and returns the new length of this array.

[3,4,5].unshift(1,[2,2]) // returns 5


GeorgeHernandez.comSome rights reserved