Web Development Tutorials




  
  

Array Methods

Array objects are supplied with several methods for common processing of elements in an array and between arrays.

Sorting Arrays

Elements in an array appear in the order in which they are loaded. You can, however, arrange them in ascending or descending alphabetic or numeric sequence by applying the sort methods shown below.


[array =] array.sort()                          //Sort alphabetic ascending
[array =] array.reverse()                       //Sort alphabetic descending

[array =] array.sort(function(a,b){return b-a}) //Sort numeric ascending
[array =] array.sort(function(a,b){return a-b}) //Sort numeric descending
Figure 6-9. General formats to sort an array.

Elements are arranged in ascending alphabetic sequence by applying the sort() method to an array. Elements are arranged in descending alphabetic sequence by applying the reverse() method after applying the sort() method. Arrays are sorted in-place, replacing the current order of elements, unless you assign the resulting sorted elements to a different array.

Below, array myArray is loaded with 10 numbers in no particular order. Functions are provided to arrange the elements in ascending or descending order, replacing the current sequence of elements with the sorted elements.


var myArray = new Array();

function loadArray()
{
	myArray[0] = 25;
	myArray[1] = 54;
	myArray[2] = 13;
	myArray[3] = 10;
	myArray[4] = 75;
	myArray[5] = 47;
	myArray[6] = 23;
	myArray[7] = 85;
	myArray[8] = 80;
	myArray[9] = 36;
}

function originalArray()
{
  document.getElementById("originalArrayOut").innerHTML = "";
  for (i=0; i < myArray.length; i++) {
    document.getElementById("originalArrayOut").innerHTML += myArray[i] + " ";
  }
}

function SortedArray()
{
  document.getElementById("sortedArrayOut").innerHTML = "";
  myArray.sort( function(a,b){return a-b} );
  for (i=0; i < myArray.length; i++) {
    document.getElementById("sortedArrayOut").innerHTML += myArray[i] + " ";
  }
}

function ReversedArray()
{
  document.getElementById("reversedArrayOut").innerHTML = "";
  myArray.sort( function(a,b){return a-b} );
  myArray.reverse();
  for (i=0; i < myArray.length; i++) {
    document.getElementById("reversedArrayOut").innerHTML += myArray[i] + " ";
  }
}

function init()
{
  loadArray();   
    
  var originalArrayBtn = document.getElementById("originalArrayBtn");
  originalArrayBtn.onclick=originalArray;

  var sortedArrayBtn = document.getElementById("sortedArrayBtn");
  sortedArrayBtn.onclick=sortedArray;
  
  var reversedArrayBtn = document.getElementById("reversedArrayBtn");
  reversedArrayBtn.onclick=reversedArray;
}

window.onload=init;


<input type="button" value="Original Array" id="originalArrayBtn"/> = 
  <span id="originalArrayOut"></span><br/>
<input type="button" value="Sorted Array" id="sortedArrayBtn"/> = 
  <span id="sortedArrayOut"></span><br/>
<input type="button" value="Reversed Array" id="reversedArrayBtn"/> = 
  <span id="reversedArrayOut"></span><br/>

Listing 6-8. Code to sort an array.

The following buttons call the previous functions to arrange and display elements of myArray.

=
=
=

Figure 6-10. Sorting an array.

By default, sorting takes place alphabetically. To sort numerically, the sort method must be passed an argument indicating the comparison that should take place between any two values as they are being arranged. The argument is in the form of a function call, technically, an application of a function literal, or lambda function. In short, methods that sort an array numerically in ascending and descending sequence are given above in Figure 6-9.

Converting an Array to a String

In the example functions shown above, the contents of array myArray are written to the page by iterating through the elements and concatenating their values within the output areas. JavaScript provides the join() method to automatically do exactly this.


string = array.join([separator])
Figure 6-11. General format for join() method.

When applied to an array, the join() method concatenates all the element values to a string, separating the elements with a comma unless an optional separator string is given. The separator join(" : ") is applied in the following function to display myArray, after having first sorted it.


=

Figure 6-12. Joining array elements to a string.


function joinedArray()
{
  myArray.sort();
  document.getElementById("joinedArrayOut").innerHTML = myArray.join(" : ");
}

function init()
{
  loadArray();   
    
  var joinedArrayBtn = document.getElementById("joinedArrayBtn");
  joinedArrayBtn.onclick=joinedArray;

}

window.onload=init;

<input type="button" value="Joined Array" id="joinedArrayBtn"/> = 
<span id="joinedArrayOut"> </span>

Listing 6-9. Code to join array elements to a string.

Creating a Subset of an Array

The slice() method returns a subset of elements of an array. Its general format is shown below.


array = array.slice(start,end)

Figure 6-13. General format for slice() method.

The start argument gives the starting element of the subset extracted from the array (counting from 0); the end argument gives the ending element (up to but not including this element) of the subset. If only the start argument is supplied, then all subsequent elements are retrieved from the array. The sliced subset of elements can be assigned to a new array or reassigned to the original array to replace it.

The following function retrieves a subset of elements from myArray. It returns the subset beginning with element 3 (the fourth element) and ending "short of" element 7 (that is, through element 6). The subset is assigned to a second array and displayed.


=

Figure 6-14. Extracting a subset of elements of an array.


function slicedArray()
{
  myArray.sort();
  var slicedArray = myArray.slice(3,7);
  document.getElementById("slicedArrayOut").innerHTML = slicedArray.join(" : ");
}
function init()
{
  loadArray();   
    
  var slicedArraybtn = document.getElementById("slicedArraybtn");
  slicedArraybtn.onclick=slicedArray;

}

window.onload=init;

<input type="button" value="Sliced Array" id="slicedArraybtn" /> = 
<span id="slicedArrayOut">/span>

Listing 6-10. Code to extract a subset of elements of an array.

Deleting and Adding Array Elements

Elements can be removed from or added to an array with the splice() method whose general format is shown below.


array.splice(start,n [,value ...])

Figure 6-15. General format for splice() method.

Argument start gives the starting position (counting from 0) for removing elements from or adding elements to the array; argument n gives the number of elements to remove. When adding elements to an array, a comma-delimited list of values is supplied; in this case, n is set to 0 (zero).

The following function, for example, removes the last five elements of MyArray and displays the resulting array as a joined string.


=

Figure 6-16. Splicing an array to remove elements.


function splicedArray()
{
  myArray.sort();
  myArray.splice(5, myArray.length - 1);
  document.getElementById("splicedArrayOut").innerHTML = myArray.join(" : ");
}

function init()
{
  loadArray();   
    
  var splicedArrayBtn = document.getElementById("splicedArrayBtn");
  splicedArrayBtn.onclick=splicedArray;

}

window.onload=init;

<input type="button" value="Spliced Array" id="splicedArrayBtn"/> = 
<span id="splicedArrayOut"></span>

Listing 6-11. Code to splice an array to remove elements.

The splice() method can be used to insert items into an existing array. Any third and subsequent arguments supplied to the method adds the values beginning at the start position. The following functions adds five new numbers (1, 2, 3, 4, 5) beginning at the fifth position in myArray.


=

Figure 6-17. Splicing an array to add elements.


function splicedArray()
{
  myArray.sort();
  myArray.splice(5,0,1,2,3,4,5);
  document.getElementById("splicedArrayOut").innerHTML = myArray.join(" : ");
}

function init()
{
  loadArray();   
    
  var splicedArrayBtn = document.getElementById("splicedArrayBtn");
  splicedArrayBtn.onclick=splicedArray;

}

window.onload=init;


<input type="button" value="Spliced Array" id="splicedArrayBtn"/> = 
<span id="splicedArrayOut"></span>>

Listing 6-12. Code to splice an array to add elements.

Converting Array Elements to Strings

By applying the toString() method to an array, all of its elements are converted to string values. If the array is subsequently output, its values are displayed as a comma-separated list.


string = array.toString()

Figure 6-18. General format for toString() method applied to an array.

The following function converts the numbers in myArray into string values and displays them as a comma-separated list.


=

Figure 6-19. Converting an array to a string.


function stringArray()
{
  myArray.sort();
  myArray.toString();
  document.getElementById("stringArrayOut").innerHTML = myArray;
}

function init()
{
  loadArray();   
    
  var stringArrayBtn = document.getElementById("stringArrayBtn");
  stringArrayBtn.onclick=stringArray;

}

window.onload=init;

<input type="button" value="String Array" id="stringArrayBtn"/> = 
<span id="stringArrayOut"></span>

Listing 6-13. Code to convert an array to a string.

Creating Arrays from Strings

The split() method was used previously to separate a string into substrings for loading into an array. It provides an easy alternative, then, to the formal method of loading arrays by specifying the contents of individual elements. Recall that substrings are identified by a delimiter character which identifies separate data values for loading into an array.

For instance, the values for myArray can originate as the following string, with values delimited by commas.


mumberString = "10,13,23,25,36,47,54,75,80,85";

By using the split() method, these values can be loaded into separate elements of an array with a single line of code.


var numberString = "10,13,23,25,36,47,54,75,80,85";
var myArray = numberString.split(",");

Listing 6-14. Code to load an array from a string.


Figure 6-20. An array loaded from a string.

Any delimiter character can be used as long as it is not part of the actual data values being split into an array. If no delimiter is specified, the entire string occupies a single element of the array; if a null, or empty, delimiter ("") is used, then each character occupies a separate element of the array.

Arrays loaded in this manner are string arrays. In order to work with array elements as numbers it is necessary to convert them. Iterate through the array applying the parseInt() or parseFloat() method to each element.


var numberString = "10,13,23,25,36,47,54,75,80,85";
var myArray = numberString.split(",");

for (i=0; i<myArray.length; i++) {
  myArray[i] = parseInt(myArray[i]);
}

Listing 6-15. Code to load an array with numbers from a string.


TOP | NEXT: Objects as Associative Arrays