sveti petar
sveti petar

Reputation: 3797

Sort array by values of other array in Javascript?

I'm having trouble sorting a hand of cards with Javascript, partly due to the fact I keep trying to figure out when to use an array and when an object, and partly because Javascript just isn't as easy to work with as, say, PHP when it comes to arrays. I also can't use jQuery because this is server-side Node.js code and I want to stick to pure Javascript.

This is how the hand is formatted to begin with:

[ 'QD', '8H', 'QS', '10C', '10D', '7D', 'KH', '9S' ]

As you see, each card is noted as rank+suit, so QD is Queen of Diamonds, 8H is 8 of Hearts etc. It is not acceptable to sort them alphabetically. The way I need to sort them is by values given in the following array, from highest to lowest:

[ QD: 25,
  '8H': 32,
  QS: 45,
  '10C': 17,
  '10D': 27,
  '7D': 21,
  KH: 36,
  '9S': 43 ]

As a side note, can someone tell me why some of the card names have 's around them and some don't? The above is the output from console.log, and all 'card names' were initialized the same way.

So the array should look like:

[ 'QS', '9S', 'KH', '8H', '10D', 'QD', '7D', '10C' ]

I know what needs to be done logically but I don't know how to accomplish it in Javascript. In PHP, I would sort the array of card values, then use a foreach loop to go through it, where key would be the card; then create a hand array with the keys of this array. But in Javascript I'm not sure how to even get the keys for the array.

Upvotes: 2

Views: 984

Answers (1)

Gopherkhan
Gopherkhan

Reputation: 4342

You could do something like this:

var ranks = { 
  'QD': 25,
  '8H': 32,
  'QS': 45,
  '10C': 17,
  '10D': 27,
  '7D': 21,
  'KH': 36,
  '9S': 43 };

var toSort = [ 'QD', '8H', 'QS', '10C', '10D', '7D', 'KH', '9S' ];

toSort.sort(function(left, right) {
   return ranks[right] - ranks[left]; // descending order
});

Alternatively, you could just use the ranks map, and get the suits array via:

Object.keys(ranks).sort(...same_as_above...)

Upvotes: 2

Related Questions