Skip to content

Instantly share code, notes, and snippets.

@stephencweiss
Last active December 10, 2018 15:13
Show Gist options
  • Save stephencweiss/4a8e9a1a5d2ae1b5fc99a3b4d68e86e6 to your computer and use it in GitHub Desktop.
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
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