HTML and CSS Reference
In-Depth Information
of these items:
reverse()
and
sort()
. The
reverse()
method, as the name suggests,
reverses the order of items in an array, making the last items first and the first items last.
In the following set of commands, the
reverse()
method is used to change the order of
the values in the
weekDay
array:
var weekDay = [“Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”];
weekDay.reverse();
After running the
reverse()
method, the
weekDay
array would contain the items in the
following order:
Sat
,
Fri
,
Thu
,
Wed
,
Tue
,
Mon
, and finally,
Sun
. As a result, the expres-
sion
weekDay[5]
would return the text string
Mon
under the reversed array.
Sorting an Array
The
sort()
method rearranges array items in alphabetical order. This can cause unex-
pected results if you apply the
sort()
method to data values that are not usually sorted
alphabetically. For example, applying the command
weekDay.sort();
to the
weekDay
array causes the array to store the weekday abbreviations in the order
Fri
,
Mon
,
Sat
,
Sun
,
Thu
,
Tue
,
Wed
—which is likely not what you want.
Also, if you apply the
sort()
method to numeric values, the method treats the values
as text strings and sorts them in order by their first digits, rather than by their true numeri-
cal values. Thus, applying the
sort()
method to the array
var x = [3, 45, 1234, 24];
x.sort();
would result in the order
1234
,
24
,
3
,
45
because this is the order of those numbers
when sorted by their first digits. To correctly sort numeric data, you must create a
compare function
that compares the values of two adjacent array items. The general
form of a compare function is
function
fname
(
a
,
b
) {
return a negative, positive, or 0 value based on the comparison
between a and b
}
where
fname
is the name of the compare function, and
a
and
b
are two parameters used
by the function. These parameters are compared to determine which is greater. The func-
tion then returns a negative, positive, or 0 value based on that comparison. For example,
the following compare function returns the numeric difference between the
a
and
b
parameters:
function numSort(a, b) {
return a - b;
}
The value returned by the function is the basis by which two adjacent array items are
sorted. If the value of the difference,
a ‑ b
, is 0 or positive, the order of the two items
remains unchanged; but if the difference is negative, the two items swap positions in
the array. JavaScript uses the compare function to reorder every pair of items in the array
until no items are left that require swapping.
To apply a compare function to the
sort()
method, you use the expression
array
.sort(
function
)
where
function
is the name of the compare function. For example, to use the numSort()
compare function to sort the
x
array in ascending numeric order, you'd run the following
command:
x.sort(numSort)