17

I have an array with subarrays and wish to sort numerically and descending by the first item in the subarrays. So for example, I wish to take the following array"

array = [[2,text],[5,text],[1,text]]

and sort it to become

array = [[5,text],[2,text],[1,text]]

Is there any simple function to use? Thanks!

3 Answers 3

25
array = [[2,text],[5,text],[1,text]];
array.sort(function(a,b){return a[0] < b[0]})
Sign up to request clarification or add additional context in comments.

5 Comments

i'm glad that i could help sir,
Can this be set up generically, so that I can pass it which element to sort on?
@jlbriggs you can use closures for this like for example function genericSort(index, arr) {array.sort(function(a,b){return a[index] < b[index]})} and then you can call it as array = [[2,3],[5,1],[1,2]];genericSort(0, array); /*this will sort on the first index*/ genericSort(1, array); and this one on the second hope this could help
doesn't work. The right answer is below, with a "-" instead of a "<" !
@xem depends on browser. FF accepts true/false and +/-. Spyware (Chrome and its derivatives), and Safari/Webkit, only accept +/-
15
array = [[2,text],[5,text],[1,text]];
array.sort(function(a,b){return a[0] - b[0]})

working of the sort function
if the function returns

  • less than zero, sort a before b
  • greater than zero, sort b before a
  • zero, leave a and b unchanged with respect to each other

Additional information at source.

1 Comment

You can shorten that to array.sort((a,b) => a[0] - b[0])
0
array.sort(key=lambda x: x[0], reverse=True)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.