# Sorting of array in JavaScript

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 order. Here is the basic syntax of the sort function.
``Array.sort();``
Now let us try to create an array and then display them to see the elements and their order. After this we will apply sort() function and then again we will display the elements of the array to check the order. Here is the code.
``````
<script language="javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";q
for (i=0;i<scripts.length;i++)
{
document.write(scripts[i] + "<br >");
}

scripts=scripts.sort();
document.write("<br>--Now after the sort---<br>");
for (i=0;i<scripts.length;i++)
{
document.write(scripts[i] + "<br >");
}
</script>
``````

## In the order of length of the element

We can define our sorting algorithm in a function and JavaScript will use the function to sort the array. There are some condition the function must satisfy. Here they are

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.
If the returned number is < 0 then first argument should appear before the second argument.

If the returned number is greater than 0 then first argument should appear after the second argument.

If the returned number is equal to 0 then both the arguments should be equal.

Let us try to sort the array elements by their lengths using the function. Here is the code Here is the code.
``````
<script language="javascript">
function bylength(a1,a2){
if(a1.length < a2.length)
return -1;
if(a1.length > a2.length)
return 1;
if(a1.length == a2.length)
return 0;

}
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
for (i=0;i<scripts.length;i++)
{
document.write(scripts[i] + "<br >");
}
document.write("<br>-----<br>");

scripts=scripts.sort(bylength);q
for (i=0;i<scripts.length;i++)
{
document.write(scripts[i] + "<br >");
}
</script>``````

## Subscribe to our mailing list

* indicates required
Subscribe to plus2net

More on JavaScript Arrays : Create , display and Applications

Post Comment This is for short comments only. Use the forum for more discussions.

## Subscribe to our mailing list

* indicates required
Subscribe to plus2net