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

130
Views
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 answers
Answer question

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