How can I sort a list of lists by order of the last element?
Here is my best attempt so far:
var mylist = [ [1, 'c'], [3, 'a'], [5, 'b']];
mylist.sort(function(a,b){return a[1]-b[1];});
My call to sort
has not effect, and mylist
remains in the same order.
var mylist = [ [1, 'c'], [3, 'a'], [5, 'b']];
mylist.sort(function(a,b){return a[1].localeCompare(b[1]);});
console.log(mylist)
Use a[1].localeCompare(b[1])
to sort the list in the ascending order or b[1].localeCompare(a[1])
for other way round. This way you will be comparing two strings. You were trying to subtract one string from the other which return NaN
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With