The sort()
method
sorts an array.
By default,
the method sorts
the array in the ascending order.
The sorting happens according
to the order in which the string versions
of the array elements
will appear in a dictionary.
Note that the sort
method
directly mutates the numbers
array.
We don't have to assign the sorted array.
In the example given above,
because the sort
method
looks at the array elements as strings,
"11" comes before "2" in
the code given below.
We can supply a function as an
argument to the sort()
method.
The function can be used
to change the sort order.
The function will be invoked on
every two elements in the array.
In the example above,
the function sortNumbers
is invoked
by passing two elements of numbers
as arguments.
Based on the value returned
by the function,
sort()
decides the positions
of the two elements.
-
If the return value is greater than 0
it means that a
should come after b
.
-
If the return value is lesser than 0
it means that a
should come before b
.
-
If the return value is equal to 0
it means that the positions of a
and b
need not be changed.