JavaScript Reference: Arrays


Creating Arrays

Arrays should be surrounded by square brackets [...] with each value in the array separated by a comma (do not place a comma after the last value). The values within the array can be of any type, and a combination of types can exist in one array.
// An array containing numbers, strings, and a function:
var sampleArray = [ 5, 1, 'hello', function(x) { return x+5 }, -4, 'bye', 0 ]

An array can also contain an array (this is called nesting), which in turn may contain more arrays:
// An array containing the number 6, the array [4,3,'hi'], and the nested array [3,[2,1]]:
var nestedArray = [ 6, [ 4, 3, 'hi' ], [ 3, [ 2, 1 ] ] ]

Indices

The values in an array can be referenced by their index. The first value in an array has index 0, the next has index 1, and so on. When new values are added to the beginning of an array, the index of each value changes to reflect their current order. A particular value in an array can be referred to by providing the name of the array followed by the value's index in square brackets:
var sampleArray = [ 5, 1, 'hello', function(x) { return x+5 }, -4, 'bye', 0 ]
console.log( sampleArray[0], sampleArray[2], sampleArray[3] )
would result in
5 'hello' [Function]

To call a function in an array, use its index reference in place of its name:
var powerFunctions = [ function(x){return x^0}, function(x){return x}, function(x){return x*x}, function(x){return x*x*x},  ]
var fourSquared = powerFunctions[2](4)  	// passes value 4 to third function in array
console.log( fourSquared )
would result in
16

Indices can also be used to redefine a particular value in an array:
var anotherArray = [ 2, 4, 6, 7, 10 ]
anotherArray[3] = 8
anotherArray[4] = 'ten'
console.log( anotherArray )
would result in
[ 2, 4, 6, 8, 'ten' ]

Array Properties

length

  • Use: Get the number of elements in an array (note that subarrays are counted as a single element)
  • Format: arrayName.length
  • Example:
    var dogBreeds = ['boxer', 'rottweiler', 'afghan', 'silky terrier', 'papillon', 'chow chow', 'golden retriever' ]
    var numberOfDogs= dogBreeds.length
    console.log( numberOfDogs )
    would result in
    7
  • Example:
    var evens = [ 2,4,6,8,10,12,14,16,18,20 ]
    
    var sum = 0
    for ( i=0; i<evens.length; i++ ) {
    	sum = sum + evens[i]
    }
    console.log( "The sum of all even numbers from 1 to 20 is "+sum )
    would result in
    The sum of all even numbers from 1 to 20 is 110

Array Methods

A summary of available methods for working with arrays:

indexOf

  • Use: Find first instance of an element in an array
  • Format: arrayName.indexOf( element )
  • Example:
    var anotherArray = [ 2, 4, 6, 7, 6, 8, 11, 10 ]
    anotherArray.indexOf(6) 	// returns 2 

lastIndexOf

  • Use: Find last instance of an element in an array
  • Format: arrayName.lastIndexOf( element )
  • Example:
    var anotherArray = [ 2, 4, 6, 7, 6, 8, 11, 10 ]
    anotherArray.lastIndexOf(6) 	// returns 4 

push

  • Use: Add element(s) to the end of an array
  • Format: arrayName.push( element1, element2, ... )
  • Example:
    var dogBreeds = ['boxer', 'rottweiler', 'afghan', 'silky terrier', 'papillon', 'chow chow', 'golden retriever' ]
    dogBreeds.push( 'basset hound' )
    console.log( dogBreeds )
    dogBreeds.push( 'poodle', 'beagle' )
    console.log( dogBreeds )
    would result in
    [ 'boxer', 'rottweiler', 'afghan', 'silky terrier', 'papillon', 'chow chow', 'golden retriever', 'basset hound' ]
    [ 'boxer', 'rottweiler', 'afghan', 'silky terrier', 'papillon', 'chow chow', 'golden retriever', 'basset hound', 'poodle', 'beagle' ]

unshift

  • Use: Add element(s) to the beginning of an array
  • Format: arrayName.push( element1, element2, ... )
  • Example:
    var dogBreeds = ['boxer', 'rottweiler', 'afghan', 'silky terrier', 'papillon', 'chow chow', 'golden retriever' ]
    dogBreeds.unshift( 'dachshund' )
    console.log( dogBreeds )
    would result in
    [ 'dachshund', 'boxer', 'rottweiler', 'afghan', 'silky terrier', 'papillon', 'chow chow', 'golden retriever' ]

shift

  • Use: Removes and returns first element from an array
  • Format: arrayName.shift( )
  • Example:
    var someNumbers = [ 4, 8, 10, 17, 20 ]
    var firstEntry = someNumbers.shift()
    console.log( someNumbers, firstEntry )
    would result in
    [ 8, 10, 17, 20 ] 4

pop

  • Use: Removes and returns last element from an array
  • Format: arrayName.pop( )
  • Example:
    var someNumbers = [ 4, 8, 10, 17, 20 ]
    var lastEntry = someNumbers.pop()
    console.log( someNumbers, lastEntry )
    would result in
    [ 4, 8, 10, 17 ] 20

concat

  • Use: Create a new array by joining two existing arrays
  • Format: newArray = oldArray1.concat( oldArray2 )
  • Example:
    var evens = [ 2, 4, 6, 8, 10 ]
    var odds = [ 1, 3, 5, 7, 9 ]
    var allNumbers = evens.concat(odds)
    console.log( allNumbers )
    would result in
    [ 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 ]

every

  • Use: Test all array elements for a property
  • Format: arrayName.every( function )
  • Example:
    function areTheyEven(element, index, array) {
    	return element%2 == 0
    }
    var test1 = [ 2, 4, 6, 8, 10 ].every(areTheyEven); 		
    var test2 = [ 3, 6, 2, 1, 12 ].every(areTheyEven);
    console.log( test1, test2 )
    would result in
    true false

some

  • Use: Test whether any elements in an array have a certain property
  • Format: arrayName.foreach( function )
  • Example:
    function areTheyEven(element, index, array) {
    	return element%2 == 0
    }
    var test1 = [ 2, 3, 5, 7 ].some(areTheyEven); 		
    var test2 = [ 3, 5, 7 ].some(areTheyEven);
    console.log( test1, test2 )
    would result in
    true false

filter

  • Use: Create new array by filtering existing array by a property
  • Format: newArray = oldArray.filter( function )
  • Example:
    function areTheyEven(element, index, array) {
    	return element%2 == 0
    }
    var justEvens = [ 1,2,3,4,5,6,7,8,9,10 ].filter(areTheyEven); 		
    console.log( justEvens )
    would result in
    [ 2, 4, 6, 8, 10 ]

foreach

  • Use: Execute a function on all array elements
  • Format: arrayName.foreach( function )
  • Example:
    function plusOne(element, index, array) {
      array[index] = element+1;
    }
    
    var smallArray = [1,2,3]
    smallArray.forEach(plusOne);
    console.log(smallArray)
    would result in
    [ 2, 3, 4 ]

map

  • Use: Create a new array by executing a function on the elements of an existing array
  • Format: newArray = oldArray.map( function )
  • Example:
    var smallNumbers = [ 1,2,3,4,5,6,7,8,9,10 ]		
    var perfectSquares = smallNumbers.map( function(x){ return x*x } )
    console.log(perfectSquares)
    would result in
    [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]

reduce

  • Use: Apply accumulator function to array elements from left to right
  • Format: arrayName.reduce( function )
  • Example:
    var someNumbers = [ 0, 1, 2, 3, 4, 5 ]
    
    var sum = someNumbers.reduce( function(previousValue, currentValue, index, array) {
      console.log(currentValue)
      return previousValue + currentValue;
    })
    
    console.log( sum )
    would result in
    1
    2
    3
    4
    5
    15
  • Example:
    var grades = [ 84, 89, 92, 78, 95, 67, 81 ]
    
    var totalPoints = grades.reduce( function(previousValue, currentValue, index, array) {
      return previousValue + currentValue;
    })
    
    var average = totalPoints/grades.length
    
    console.log(totalPoints, average)
    would result in
    586 83.71428571428571

reduceRight

  • Use: Apply accumulator function to array elements from right to left
  • Format: arrayName.reduceRight( function )
  • Example:
    var someNumbers = [ 0, 1, 2, 3, 4, 5 ]
    
    var sum = someNumbers.reduceRight( function(previousValue, currentValue, index, array) {
      console.log(currentValue)
      return previousValue + currentValue;
    })
    
    console.log( sum )
    would result in
    4
    3
    2
    1
    0
    15

join

  • Use: Create a string of all elements in an array, with an optional separator
  • Format: newString = arrayName.join( separator = 'sepString' )
  • Example:
    var mixedArray = [ 1, 'hello', 3, 'dogs', 4+5, 0 ]
    var mixedString = mixedArray.join(separator='...')
    console.log(mixedString)
    would result in
    1...hello...3...dogs...9...0

reverse

  • Use: Reverse the order of elements in an array
  • Format: arrayName.reverse()
  • Example:
    var smallNumbers = [ 1, 2, 3, 4, 5, 6 ]
    smallNumbers.reverse()
    console.log( smallNumbers )
    would result in
    [ 6, 5, 4, 3, 2, 1 ]

sort

  • Use: Sort elements in array by Unicode code points or by specified sorting function
  • Format: arrayName.sort( optionalFunction )
  • Notes: Works well for sorting numerical elements; strings are sorted by Unicode, which may not be alphabetical
  • Example:
    var mixedNumbers = [ 5, 1, -7, 18, 30, -11, 0, Math.PI, 9, 3, -2 ]
    mixedNumbers.sort()
    console.log( mixedNumbers )
    would result in
    [ -11, -2, -7, 0, 1, 18, 3, 3.141592653589793, 30, 5, 9 ]
  • Example:
    var mixedArray = [ 1, 'hello', 3, 'dogs', 4+5, 0 ]
    mixedArray.sort()
    console.log( mixedArray )
    would result in
    [ 0, 1, 3, 9, 'dogs', 'hello' ]

toString

  • Use: Create a string of all elements in an array separated by a comma
  • Format: newString = arrayName.toString()
  • Example:
    var mixedArray = [ 1, 'hello', 3, 'dogs', 4+5, 0 ]
    var mixedString = mixedArray.toString()
    console.log(mixedString)
    would result in
    1,hello,3,dogs,9,0

toLocaleString

  • Use: Create a string of all elements in an array, with date/time elements converted to locale
  • Format: newString = arrayName.toString()
  • Example:
    var arrayName = ['It is now', Date()]
    var stringName = arrayName.toLocaleString()
    alert( stringName )
    Try it

splice

  • Use: Add or remove elements at a specific location of an array
  • Format: arrayName.splice( startIndex, numberOfElementsToRemove, elementsToAdd )
  • Example:
    // Add a new dog to the array after the second element
    var dogBreeds = ['boxer', 'rottweiler', 'afghan', 'silky terrier', 'papillon' ]
    dogBreeds.splice( 2, 0, 'corgi')
    console.log( dogBreeds )
    would result in
    [ 'boxer', 'rottweiler', 'corgi', 'afghan', 'silky terrier', 'papillon' ]
  • Example:
    // Remove two elements from the array, starting after the second element
    var dogBreeds = ['boxer', 'rottweiler', 'afghan', 'silky terrier', 'papillon' ]
    dogBreeds.splice( 2, 2 )
    console.log( dogBreeds )
    would result in
    [ 'boxer', 'rottweiler', 'papillon' ]