0

Someone asked me how to sort the array below as per the rules of the card game using a generic method. Based on my research on the rules of card games, the small number comes first, and the names, it always arranged as Jack, Queen, King

This is the array below

 const cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen']

Required Output

[2,3,5,6,8,'Jack','Queen','King']

So I just wrote a basic function to sort it like this

function sortCard(){
    cards.sort();
    console.log(cards);
}
 sortCard();

It gave me the required output

[2,3,5,6,8,'Jack','Queen','King']

Though my approach is wrong and does not answer the question.

So how can I sort the card as per the rules of the card game using a generic method?

Isak
  • 11
  • 1
  • What do you mean by "a generic method"? Also, [MDN's documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) (and countless questions and answers here on SO) show how to provide a custom callback function to `sort`. If that's what you're asking, please refer to those before posting. – T.J. Crowder Apr 09 '22 at 13:01
  • Side note: There's usually also an `Ace`, which is higher than `King`, and which would get sorted incorrectly by your code that relies on a lexicographic sort. – T.J. Crowder Apr 09 '22 at 13:01
  • for example https://stackoverflow.com/questions/8663163/sorting-objects-according-to-a-specific-rule – mplungjan Apr 09 '22 at 13:03
  • 1
    Sounds like you will need a custom compare function, in which you will sort.. Overall you can sort regularly the numbers, but names need special handling. You can see example here how to create comparator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – David Constantine Apr 09 '22 at 13:04

3 Answers3

2

well you can use an object to attribute a numeric value to 'Jack' or 'King'

const reference={Jack:10,Queen:11,King:12,Ace:13}
const cards = ['Jack', 8, 'Ace', 2, 6, 'King', 5, 3, 'Queen']
const sorter=(a,b)=>(reference[a]||a)-(reference[b]||b)
//reference is only for words so if it's not one of the words, it choses the value itself to do the math
console.log( cards.sort(sorter) )
The Bomb Squad
  • 4,192
  • 1
  • 9
  • 17
0

Here is a simple sort function

const sortOrder = [2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"]

const cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen']

cards.sort((a,b) => sortOrder.indexOf(a) - sortOrder.indexOf(b))

console.log(cards)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

You can pass a function to sort to control the sorting. See the MDN docs for more information

For example, if you want to sort the months of the year:

function sortMonths(arrayOfMonths){
    order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    return [...arrayOfMonths].sort((a, b) => order.indexOf(a) - order.indexOf(b))
}
console.log(sortMonths(['Dec', 'May', 'Jul', 'Jun']))
Cameron Ford
  • 202
  • 1
  • 6