Last active
June 14, 2023 19:38
-
-
Save gn-bcampbell/9280ef688f551b6b591dab9671d33154 to your computer and use it in GitHub Desktop.
Sorting array of numbers in javascript
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
// 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