Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda