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.
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.
- 1 use > or < instead of - – juvian Commented Jan 4, 2016 at 20:31
2 Answers
Reset to default 18
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
.
var mylist = [ [1, 'c'], [3, 'a'], [5, 'b']];
// to sort by 1st NUMBER element; minus also used for object such as date
mylist.sort(function(a,b){return a[0] - b[0];});
// to sort by 2nd STRING element with >.
// strings can be compared based on alphabetical order with > or <,
// but not with a math order operator -, which is supposed to used for comparison between number or date.
mylist.sort(function(a,b){return a[1] > b[1];});
Above mentioned examples gives sorting in ascending order, here I note what I understand for who may need: to sort in ascending order [1,9,7] to [9,7,1], we could image there is an empty array[], then we'll just put each element one by one to this array in the right order (based on comparison with existing elements).
function(a,b) { return b - a; }
here a is existing one, b is the one we are going to put in the array.
- if return > 0 (true) >> [b,a] , we could consider the return value as the order of a, positive/true means a should put later, that's the sort() means.
- if return <=0 (false) >> [a,b]
for [1,9,7], the loop will be:
[]
// to put 1
[1]
// to put 9
a = 1, b = 9, b - a > 0 ==> [9,1]
// to put 7
a = 9, b = 7, b - a < 0 ==> [9,7,1]
a = 1, b = 7, b - a > 0 ==> [9,7,1]