Last active
December 10, 2018 15:13
-
-
Save stephencweiss/4a8e9a1a5d2ae1b5fc99a3b4d68e86e6 to your computer and use it in GitHub Desktop.
A basic ascending and descending use case for sorting an array with Javascript's built-in sort utilizing a custom sort function
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
const arr = [4,1,2,5,3,2]; | |
function ascendingSort(a, b) { | |
if (a < b) { return -1 } | |
return 1 | |
}; | |
function descendingSort(a, b) { | |
if (a < b) { return 1 } | |
return -1 | |
}; | |
console.log(`Native --> `, arr.sort()); // [ 1, 2, 2, 3, 4, 5 ] | |
console.log(`Ascending -> `, arr.sort(ascendingSort)); // [ 1, 2, 2, 3, 4, 5 ] | |
console.log(`Descending -> `, arr.sort(descendingSort)); // [ 5, 4, 3, 2, 2, 1 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment