Created
December 10, 2018 15:14
-
-
Save stephencweiss/f4d18ed1a97129d07d8066debcf4a1fc to your computer and use it in GitHub Desktop.
Example of multiple condition sort method for a nested array -- sorts numbers descending then letters ascending (in event of tie)
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 nestedArray = [ [ 'm', 1 ], [ 'i', 4 ], [ 's', 4 ], [ 'p', 2 ] ]; | |
function descNumbersAscChar(arrA, arrB) { | |
if (arrA[1] > arrB[1]) { return -1 } | |
else if (arrA[1] === arrB[1]) { | |
if (arrA[0] < arrB[0]) { return -1 } | |
else if (arrA[0] > arrB[0]) { return 1} | |
} | |
else if (arrA[1] < arrB[1]) { return 1 } | |
else { | |
console.log('Uncaught situation!') | |
return 1 | |
} | |
}; | |
console.log(nestedArray.sort(descNumbersAscChar)); // [ [ 'i', 4 ], [ 's', 4 ], [ 'p', 2 ], [ 'm', 1 ] ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment