Jump to main content
Menu

Array Objects

Multi-Dimensional Arrays

  • It is possible to create arrays that extend as deeply as you need.
  • For a two-dimensional array the syntax is theArray[][], so theArray[1][0] would access the first item [0] in the second position [1] of the array.

Multi-Dimensional Array Example: Generating HTML Table from Array

See the Pen JavaScript Multi-Dimensional Arrays by Jason Withrow (@jwithrow) on CodePen.

Associative Arrays

  • When an array value is indexed with a string rather than a number (e.g., theArray['test'] rather than theArray[0]), the array is referred to as an associative array.
  • The string indexes are referred to as keys.
  • An array object can have a mixture of keys and numerical indexes. However, the array object's length property ignores the keys.
  • Because they are not indexed by number, it is impossible to use a traditional for loop (which is numerically based) to extract the values assigned to those keys.
  • Instead there is a for-in loop that is used.
  • While most browsers will sequence for-in content based on the insertion sequence of the keys (the sequence they were added in the code), it is good to test cross-platform and cross-browser to ensure that behavior is consistent across all target browsers.

Associative Array Example

See the Pen JavaScript Associative Arrays by Jason Withrow (@jwithrow) on CodePen.

Array Methods

  • The following methods only work when applied to Array objects.
  • Collections / node lists will not support these approaches, with the one exception of forEach(), which does work with node lists.

forEach() Method

  • forEach() passes all the values in the array to a callback function.
  • That callback function needs one parameter (the array value) and optionally can accept parameters for the index of the array item and the entire array.

forEach() Example

const arr = [1, 2, 3];
arr.forEach(function(val, index, array) {
  console.log('Index ' + index + ': ' + val);
});

// outputs:
// Index 0: 1
// Index 1: 2
// Index 2: 3

concat() Method and the spread operator

  • Joins together existing arrays into a new array; the original arrays are not changed.
  • Many arrays can be concated together; each goes inside the (), separated by commas.
  • Subsequent modifications to the new array will not modify the original arrays.

concat() Example

const languages = ['HTML', 'CSS', 'JavaScript'];
const languages2 = ['PHP', 'Python', 'Ruby'];
const combined = languages.concat(languages2);

// creates combined array containing:
// ['HTML', 'CSS', 'JavaScript', 'PHP', 'Python', 'Ruby']

An alternative to concat() involves the spread operator, which is three dots and is used to represent all the values in an array. The above could be rewritten as:

const languages = ['HTML', 'CSS', 'JavaScript'];
const combined = [...languages, 'PHP', 'Python', 'Ruby'];

// combined array contains:
// ['HTML', 'CSS', 'JavaScript', 'PHP', 'Python', 'Ruby']

The spread operator has some other uses as well. Probably the most useful one is that it can be used when passing an array to a series of function parameters (for example, a function that accepts 6 parameters could have a 6-item array passed with just the array name prefaced with three dots).

includes() Method

  • This provides an efficient way to see if a value is in an array. A boolean is returned.
  • Two parameters are accepted. The first is the value, the second is optional and is the array position where lookup should start (defaults to 0).
  • Matching is on both value and type.
  • String comparisons are case-sensitive.
  • If the second parameter is negative, its placement is calculated from the end of the array. If the negative value exceeds the array length, the entire array is searched.
  • If the second parameter is positive and greater than the array length, false is returned.

includes() Example

const numbers = [5, 25, 110, 155, 210, 230];
const has230 = numbers.includes(230);
const has230asStr = numbers.includes('230');
console.log(has230);
console.log(has230asStr);

// has230: true
// has230asStr: false

join() Method

  • Combines all the elements within an array into a string, separated by whatever divider you specify inside of ().
  • If nothing is passed via () then the values are comma-separated by default; there are no spaces to the left or right of the commas.

join() Example

const numbers = [1, 2, 3];
const sequence = numbers.join(' then ');

// the value of sequence is:
// '1 then 2 then 3'

pop() Method

  • Removes the last item in an array.
  • Returns that removed value.
  • The length of the original array is reduced by one; the item is removed from it.
  • To remember this method I think of Pez dispensers; you "pop" them open to get one out.

pop() Example

const numbers = [1, 2, 3];
const lastItem = numbers.pop();

// the value of lastItem is 3
// numbers is now [1, 2]

push() Method

  • Adds one or more elements to the end of the array.
  • Returns the new length of the array.
  • To remember this method I also think of Pez dispensers; you "push" the chamber down when adding them.

push() Example

const numbers = [1, 2, 3];
numbers.push(10, 20);

// numbers now has 5 items in it
// numbers is [1, 2, 3, 10, 20]

reverse() Method

  • Flips the sequencing of elements in the array.
  • The first element becomes the last element and vice versa.

reverse() Example

const numbers = [1, 2, 3];
numbers.reverse();

// numbers[0] is now 3
// numbers[1] remains 2
// numbers[2] is now 1

shift() Method

  • Removes the first item in the array and returns that removed value.
  • The length of the original array is reduced by one (the item is removed from it).

shift() Example

const numbers = [1, 2, 3];
const firstItem = numbers.shift();

// the value of firstItem is 1
// numbers contains [2, 3]

slice() Method

  • Copies a portion of an array into a new array. The original array is not changed.
  • The first parameter passed is the start position for copying.
  • The second parameter passed is the end position.
  • Copying occurs up to that end position, but does not include the value at that end position.
  • If the second parameter is omitted, the copying extends to the highest numbered index in the array.
  • If a negative value is passed as the second parameter, the end position is calculated by counting backward from the end of the array by that number.
    • slice(5,-2) would copy from the item in the fifth position up to the item that is the third from the end of the array.

slice() Example

const numbers = [10, 20, 30, 40, 50];
const numbersSubset = numbers.slice(3);

// the numbersSubset array contains [40, 50]

sort() Method

  • Sorts the elements in an array.
  • All values are converted to strings and are sorted alphabetically (lexographically) in ascending order.
  • Inside of () you can also call a function that sorts the results differently.
  • Elements that are undefined are sorted to the high end of the sequence (they are moved to the end).
  • Be careful with sorting numbers via the default method because once they become strings, they can get out of sequence ("100" comes before "3").

sort() Example

const numbers = [110, 210, 310, 130, 270];
numbers.sort();

// the numbers array now sequences the values as:
// [110, 130, 210, 270, 310]

Passing a Custom Function to Sort Numbers Properly

  • The code to use is:
    theArray.sort(function (num1,num2) {
      return num1 - num2;
    });
    
  • theArray is a variable referencing the array. JavaScript handles num1 and num2 for you; it automatically assigns those to the array contents.
  • Any custom sorting function will put the second parameter first if a positive number is returned, will put the first parameter first if a negative number is returned, and will return 0 if the two are equal.
  • The custom function progresses through all the combinations of array values.
  • The end result of this sort() is a numbered list from lowest to highest. If you need to flip the sequence (from highest to lowest) use reverse() on the array following the sort().

splice() Method

  • Inserts and removes items from the array.
  • Requires at least two parameters:
    • The first parameter is the position to start at in the array for deleting and adding items.
    • The second parameter is the number of items to remove from the array (if set to 0, nothing is removed).
    • The third parameter (and any beyond the third) are new items to add at the spot in the array indicated in the first parameter.
  • Removed items are returned as an array (undefined is returned if 0 is indicated for the second parameter).

splice() Example

const numbers = [4, 6, 8, 12, 18];
const onlyFirstThree = numbers.splice(0,3);

// numbers now has [12, 18] as its content

// onlyFirstThree is an array containing:
// [4, 6, 8]

numbers.splice(2, 0, 22, 33);

// the numbers array is now:
// [12, 18, 22, 33]

unshift() Method

  • Adds one or more items to the beginning of the array.
  • Returns the updated length of the array.

unshift() Example

const numbers = [5, 15, 30, 45, 55];
numbers.unshift(10, 60);

// the numbers array is now:
// [10, 60, 5, 15, 30, 45, 55]