Saturday, April 25, 2009

Sort and Query/manipulate an array

Sorting an array

There are three methods--reverse(), sort(), and sortOn()--that allow you to change the order of an array, either by sorting or reversing the order. All of these methods modify the existing array.

The reverse() method changes the order of the array such that the last element becomes the first element, the penultimate element becomes the second element, and so on.

The sort() method allows you to sort an array in a variety of predefined ways, and even allows you to create custom sorting algorithms.

The sortOn() method allows you to sort an indexed array of objects that have one or more common properties that can be used as sort keys.

Querying an array

The four methods of the Array class--concat(), join(), slice(), toString()--all query the array for information, but do not modify the array.

The concat() and slice() methods both return new arrays, while the join() and toString() methods both return strings.

The concat() method takes a new array or list of elements as arguments and combines it with the existing array to create a new array.

The slice() method has two parameters, aptly named startIndex and an endIndex, and returns a new array containing a copy of the elements "sliced" from the existing array. The slice begins with the element at startIndex and ends with the element just before endIndex. That bears repeating: the element at endIndex is not included in the return value.


You can use the join() and toString() methods to query the array and return its contents as a string. If no parameters are used for the join() method, the two methods behave identically--they return a string containing a comma-delimited list of all elements in the array.

The join() method, unlike the toString() method, accepts a parameter named delimiter, which allows you to choose the symbol to use as a separator between each element in the returned string.

No comments:

Post a Comment