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
|
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.
<script type="text/javascript"> 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() { for (i=0; i < MyArray.length; i++) { document.getElementById("OriginalArrayOut").innerText += MyArray[i] + " "; } } function SortedArray() { MyArray.sort( function(a,b){return a-b} ); for (i=0; i < MyArray.length; i++) { document.getElementById("SortedArrayOut").innerText += MyArray[i] + " "; } } function ReversedArray() { MyArray.sort( function(a,b){return a-b} ); MyArray.reverse(); for (i=0; i < MyArray.length; i++) { document.getElementById("ReversedArrayOut").innerText += MyArray[i] + " "; } } </script> <input type="button" value="Original Array" onclick="OriginalArray()"/> = <span id="OriginalArrayOut"></span><br/> <input type="button" value="Sorted Array" onclick="SortedArray()"/> = <span id="SortedArrayOut"></span><br/> <input type="button" value="Reversed Array" onclick="ReversedArray()"/> = <span id="ReversedArrayOut"></span><br/>
The following buttons call the previous functions to arrange and display elements of MyArray.
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]) |
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.
function JoinedArray() { MyArray.sort(); document.getElementById("JoinedArrayOut").innerText = MyArray.join(" : "); } <input type="button" value="Joined Array" onclick="JoinedArray()"/> = <span id="JoinedArrayOut"></span>
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) |
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.
function SlicedArray() { MyArray.sort(); var SlicedArray = MyArray.slice(3,7); document.getElementById("SlicedArrayOut").innerText = SlicedArray.join(" : "); } <input type="button" value="Sliced Array" onclick="SlicedArray()"/> = <span id="SlicedArrayOut">/span>
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 ...]) |
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.
function SplicedArray() { MyArray.sort(); MyArray.splice(5, MyArray.length - 1); document.getElementById("SplicedArrayOut").innerText = MyArray.join(" : "); } <input type="button" value="Spliced Array" onclick="SplicedArray()"/> = <span id="SplicedArrayOut"></span>
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.
function SplicedArray() { MyArray.sort(); MyArray.splice(5,0,1,2,3,4,5); document.getElementById("SplicedArrayOut").innerText = MyArray.join(" : "); } <input type="button" value="Spliced Array" onclick="SplicedArray()"/> = <span id="SplicedArrayOut"></span>>
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() |
The following function converts the numbers in MyArray into string values and displays them as a comma-separated list.
function StringArray() { MyArray.sort(); MyArray.toString(); document.getElementById("StringArrayOut").innerText = MyArray; } <input type="button" value="String Array" onclick="StringArray()"/> = <span id="StringArrayOut"></span>
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.
NumberString = "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.
<script type="text/javascript">
var NumberString = "10,13,23,25,36,47,54,75,80,85";
var MyArray = NumberString.split(",");
</script>
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.
<script type="text/javascript">
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]);
}
</script>