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?
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) )
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)
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']))