Last active
November 1, 2021 02:10
-
-
Save DoctorDerek/e743334230815822907fa99e97d53c4a to your computer and use it in GitHub Desktop.
How to Sort an Array of Strings in JavaScript by Dr. Derek Austin 🥳 https://medium.com/p/5d59b1ac64be
This file contains hidden or 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
[1,5,10].sort() // [1, 10, 5] |
This file contains hidden or 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
const array = ["Tom","and","Jerry","cartoons"] | |
console.log(...array) // Tom and Jerry cartoons | |
// ASCII sort ascending (uppercase comes before lowercase) | |
array.sort((a,b) => a > b ? 1 : b > a ? -1 : 0) // Equivalent to default .sort() | |
console.log(...array) // Jerry Tom and cartoons | |
// Locale sort ascending (lowercase comes before uppercase) | |
array.sort((a,b) => a.localeCompare(b)) | |
console.log(...array) // and cartoons Jerry Tom |
This file contains hidden or 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
const spanish = ["comÃ", "comÃste", "comieron", "comió"] | |
spanish.sort((a,b) => a.localeCompare(b)) | |
console.log(spanish) // ["comÃ", "comieron", "comió", "comÃste"] |
This file contains hidden or 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
const array = ["Tom","and","Jerry","cartoons"] | |
console.log(...array) // Tom and Jerry cartoons | |
// ASCII sort descending (uppercase comes after lowercase) | |
array.sort((a,b) => b > a ? 1 : a > b ? -1 : 0) | |
console.log(...array) // cartoons and Tom Jerry | |
// Locale sort descending (lowercase comes after uppercase) | |
array.sort((a,b) => b.localeCompare(a)) | |
console.log(...array) // Tom Jerry cartoons and |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment