Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Intermediate
Aug 13, 1999

Sort Using a JavaScript Array

Javascript Arrays are quite versatile. One of its built-in features is the sort method. When an array is populated, you can simply call the sort method to sort by text. This works well except when you want to sort numbers, because in text, "10" is less than "2." The sort method accepts a function name as its parameter. In this function, you can specify the sort criterion. This sample shows how you can sort strings and numbers.

 
<html>
<script language=javascript>function writeArray(x){
  for (var i = 0; i <x.length; i++)
    document.write("<br>" + x[i]);
}

function myCompare(a, b){
  return a - b;
}

var a = new Array("Apples", "Strawberries", "Oranges", "Grapes");
document.write("<P>Before sort: ");
writeArray(a);
a.sort();
document.write("<P>After sort: ");
writeArray(a); 
  
var b = new Array(10,9,8,7,6,5);
document.write("<P>Before sort: ");
writeArray(b);
b.sort(myCompare);
document.write("<P>After sort: ");
writeArray(b); 

</script>
</html>

 
William Wen
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date