Richard Tran
Richard Tran

Reputation: 134

Sorting a list of lists in javascript

I'm trying to sort a list of lists in ascending order based on the second element in javascript. I'm following this answer javascript sort list of lists by sublist second entry but my list remains the same.

var a = [ [[1,2,3],10], [[5,6,7],0] ]
a.sort(function(x,y){return x[1] > y[1];});

Upvotes: 1

Views: 1504

Answers (2)

MaximilianMairinger
MaximilianMairinger

Reputation: 2424

var a = [ [[1,2,3],10], [[5,6,7],0] ]
a.sort(function(x,y){return x[1] - y[1];});

Use - instead of >.

Upvotes: 0

henrikmerlander
henrikmerlander

Reputation: 1574

Instead of comparing them with >, you should subtract one from the other using - to sort in ascending order:

var a = [ [[1,2,3],10], [[5,6,7],0] ]
a.sort(function(x,y){return x[1] - y[1];});

Upvotes: 2

Related Questions