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

138
Visualizações
Comparing color strings in typescript

I am trying to compare the following color strings with each other, i am using localeCompare for this and here we have the following colors: 'yellow', 'green', 'white' and transparent. These are saved in the variable 'status' as shown below.

How can i compare these strings the best way? Is there some kind of sort order i can set?

arr1.sort((a, b) => (a.status != null) ? a.status.localeCompare(b.status) : 0)

I tried reversing it but that was pure random stuff, i have trouble understanding this.

arr1 has multiple data stored in it, like

name: 'name'
firstName: 'firstname'
status: 'yellow'

I have a table which is rendered and in this table we want the yellow once to show first, the green second, white after that and transparent at the end of the table.

  1. yellow
  2. green
  3. white
  4. transparent

With the localeCompare, when i do the alphabetic ordering, ofcourse yellow is shown at the end of the list.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since there doesn't seem to be a clear value from the string you could use, how about defining the order yourself:

type StatusColor = 'yellow' | 'green' | 'white' | 'transparent';

const colorOrder: Record<StatusColor, number> = {
  yellow: 0,
  green: 1,
  white: 2,
  transparent: 3
};

const exampleStatus: StatusColor[] = ['yellow', 'white', 'transparent', 'green', 'green', 'yellow', 'transparent', 'yellow'];

exampleStatus.sort((a, b) => colorOrder[a] - colorOrder[b]);

console.log(exampleStatus); // [ "yellow", "yellow", "yellow", "green", "green", "white", "transparent", "transparent" ]
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