var my_array = new Array('lmn','ABC', 'qwt');
my_array.sort();
for (i=0;i<my_array.length;i++)
{
document.write(my_array[i] + "<br >");
}
output
ABC
lmn
qwt
We can sort elements of an array by using sort() function in JavaScript. This sort() function once applied changes the positions of the elements and arrange them in alphabetical or increasing order. Here is the basic syntax of the sort function.
Array.sort();
By default this sort is in lexicographical order or dictionary order. Check this example and its output.
<script>
var no_array = new Array(2, 22, 4, 24, 32);
var no_array2=no_array.sort();
for (i=0;i<no_array2.length;i++)
{
document.write(no_array2[i] + "<br >");
}
</script>
Output is here
2
22
24
32
4
The sorting is done according to string Unicode code points.
Optional Campare function
We can define our sorting algorithm in a function and JavaScript will use the function to sort the array. Function conditions are here
The function will accept two arguments and these arguments are to be compared for the algorithm. The function will return numbers based on the comparison of the two arguments. returned number is < 0 : The first argument should appear before the second argument.
returned number is > 0 : The first argument should appear after the second argument.
returned number is equal to 0 then both the arguments should be equal.
Let us try to sort the array elements now by using optional compare function.
<script>
function bylength(a1,a2){
if(a1 < a2)
return -1;
if(a1 > a2)
return 1;
if(a1 == a2)
return 0;
}
var no_array = new Array(2, 22, 4, 24, 32);
var no_array2=no_array.sort(bylength);
for (i=0;i<no_array2.length;i++)
{
document.write(no_array2[i] + "<br >");
}
</script>
Output is here
2
4
22
24
32
To change the order to descending, we must change the comparison inside the function or change this line ( swap a1,a2 ).