Skip to content

Instantly share code, notes, and snippets.

@stephencweiss
Created December 10, 2018 15:14
Show Gist options
  • Save stephencweiss/f4d18ed1a97129d07d8066debcf4a1fc to your computer and use it in GitHub Desktop.
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)
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