Wednesday, August 5, 2009

Java Script Array Sorting

Java scripts have intrigued me!!!As so far as me going to the book store and selecting java script books to learn it the old fashioned "Off the shelf" way ;) ... So some of my posts from here onwards will contain a mix and match of java scirpt/java so any anti javascript ppl please dnt take it personally :D.... I never knew java script had array sorting like whats available for us java developers. Two ways this can be accomplished..

Method 1:

//Sorts values in descending order
function compare(val1,val2){
return val2-val1;

var myarray = new Array([1,3,7,10,32,45]);

Thats about it to do sorting using arrays. Of course you could have just used myarray.sort() which would have used the default sorting mechanism and sorted the array in ascending order. You could debate here saying why do we need to define a new method just to get the sorting done. Bit too much code to do a single sorting function. Well look no further method 2 below shows how to do the same thing as above with just one line of code using the function literal capability of Javascript.

Behold Method 2!!!!!!! (Drum roll please)
Method 2:

Thats about it for now. But more to come very soon guys. So stay on the look out for all those Java script newbies like myself :).


No comments:

Post a Comment