Last active
June 21, 2017 04:35
-
-
Save json2d/ab8e1052c6b31758b87f1d16c7d15d76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const alphaAndLengthSort = (a,b) => { | |
if(a[0] == b[0]) { // if first character is equal (this is important) | |
return a.length - b.length // compare by length, if equal then | |
|| a.localeCompare(b) // compare by dictionary order | |
}else{ | |
return a.localeCompare(b) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const alphaAndLengthSort = (a, b) => { | |
if(a.startsWith(b) || b.startsWith(a)) | |
return a.length - b.length || // compare by length, if equal then | |
a.localeCompare(b); // compare by dictionary order | |
else | |
return a.localeCompare(b); // just compare by dictionary order | |
} | |
arr = ['Q1','Q11','Q111','Q12','Q15','B1111','B1'] | |
arr.sort(alphaAndLengthSort) // => ["B1", "B1111", "Q1", "Q11", "Q111", "Q12", "Q15"] | |
/* Heres why things get hairy when you sort alpha-numerics alphabetically | |
A | |
AA | |
ABC //good | |
AC | |
B | |
1 | |
11 | |
123 //bad | |
13 | |
2 | |
*/ | |
// FAILED: possible solution would be to sort numerically by converting string to base36 or base62 with https://www.npmjs.com/package/bases |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment