Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript sort list of lists by sublist second entry

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.

like image 712
kilojoules Avatar asked Jan 04 '16 20:01

kilojoules


1 Answers

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.

like image 132
void Avatar answered Oct 18 '22 09:10

void