Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
How to Sort an array using generic method

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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) )

about 4 years ago · Juan Pablo Isaza Report

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)

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!