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

Deal 13 cards

Try it

 

Then sort the hand.

Try it

First we define an Array prototype function that allows us to retrieve the Array index of a value if it exists. We will use this Array method to rank the cards according to their index values in the Array "N":

N=[2,3,4,5,6,7,8,9,10,"J","Q","K","A"]
Array.prototype.getIndex=function(val){
for(i=0;i<this.length;i++){
if(this[i]==val) return i;
}
return -1;
}

Example, remember that "A" is an Array containing a deck of cards:

var newHand=A.shuffle(200).slice(0,13);
var firstCard=newHand[0];


firstCard value is the card's suit followed by a space, followed by the face value. The value of the Ace of Hearts, for instance, would be "&hearts; A". We simply parse out the face value, it's everything following the space.

var firstCardFaceValue = firstCard.substring(firstCard.indexOf(" ")+1);

Then we look for this value in the Array "N"

var firstCardRank=N.getIndex(firstCardFaceValue);

Try it:

Hand

 

First Card

 

Rank

 

 

More