sort()
sort() method is used to sort the elements of an array in ascending or descending order. The elements of array sort as strings (in alphabetic and ascending order), by default.
Example:
var names=[garry, john, anny, harry];
names.sort();
This does not work for the numeric values as the method treats the numeric values as strings. To overcome this, there is a compareFunction.
Syntax for compareFunction
array.sort(function(a, b){return a-b});
This function returns a value (negative , positive or zero depending on arguments). Then, sort() method sorts the elements of the array using returned value.
Example:
var num = [50, 10, 16, 75, 21, 1];
num.sort(function(a, b){return b-a});
0 Comment(s)