User Defined Sort Methods
Sorting Strings
Working example: Deck of Cards
continued

First a sort function that determines the rank of each card needs to be defined.

function numSort(a,b){
return
N.getIndex(b.substring((b.indexOf(" "))+1))
-N.getIndex (a.substring((a.indexOf(" "))+1));
}

And each hand needs to be sorted into suits:

function sortHand(hand){

// Create an array for each suit
var d=new Array(),s=new Array(),h=new Array(),c=new Array();

// Loop through the hand, check the second character in each entry("h","s","d" or "c"), and convert it to an Array object reference (h,s,d or c)
for(i=0;i<hand.length;i++){
k=eval(hand[i].charAt(1));

// Add the card to the appropriate Array
k[k.length]=hand[i];
}


// Create an Array containing all four of the suits Arrays. Check that each array exists by looking for h[0],s[0],d[0] and c[0], if there is not a first entry in the array then the suit is void. In the case of a void, simply display the suit. s[0]?s.sort(numSort).join(" "):"&spades;"
reads, Does s[0] exist? If so, return the Array of spades sorted by their rank. Convert the Array to a string, separating each value with a space. If s[0] doesn't exist, return "&spades;". To add a little artistic touch, hearts and diamonds will be displayed in red. To do this, create a String prototype:
String.prototype.red=function (){
return '<font color="#f34444">'+this+'</font>';
}

theFourSuits =[
h[0]?h.sort(numSort).join(" ").red():"&hearts;".red(),
s[0]?s.sort(numSort).join(" "):"&spades;",
d[0]?d.sort(numSort).join(" ").red():"&diams;".red(),
c[0]?c.sort(numSort).join(" "):"&clubs;"
];

return theFourSuits;
}

Try it

Hand

 

By Suit

 

By Rank