Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DoctorDerek/e743334230815822907fa99e97d53c4a to your computer and use it in GitHub Desktop.
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
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
const spanish = ["comí", "comíste", "comieron", "comió"]
spanish.sort((a,b) => a.localeCompare(b))
console.log(spanish) // ["comí", "comieron", "comió", "comíste"]
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