Skip to content

Instantly share code, notes, and snippets.

@gn-bcampbell
Last active June 14, 2023 19:38
Show Gist options
  • Save gn-bcampbell/9280ef688f551b6b591dab9671d33154 to your computer and use it in GitHub Desktop.
Save gn-bcampbell/9280ef688f551b6b591dab9671d33154 to your computer and use it in GitHub Desktop.
Sorting array of numbers in javascript
// return < 0, A, B (keep order)
// return > 0, A, B (switch order)
// Note that this will mutate the original array!!
// Implement this callback to sort numbers in ASCENDING order
arrayName.sort((a, b) => {
if (a > b) return 1;
if (a < b) return -1;
})
// Implement this callback to sort numbers in DESCENDING order
arrayName.sort((a, b) => {
if (a > b) return -1;
if (a < b) return 1;
})
// Shorthand
arrayName.sort((a, b) => a - b); //ascending
arrayName.sort((a, b) => b - a); //descending
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment