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.
- yellow
- green
- white
- transparent
With the localeCompare, when i do the alphabetic ordering, ofcourse yellow is shown at the end of the list.
Advertisement
Answer
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" ]