SQL PHP HTML ASP JavaScript articles and free scripts to download
JavaScript Array

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.

Demo of displaying in alphabetical order

Here is the code.
<script language="javascript">
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 >");
}

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

Demo of displaying in the order of length

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);
for (i=0;i<scripts.length;i++)
{
document.write(scripts[i] + "<br >");
}
</script>

Google+

Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked




HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer