How to sort an array by the first element in a subarray

I have an array with subarrays and I want to sort numerically and go down the first element in subarrays. So, for example, I want to take the next 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? Thanks!

+6
source share
2 answers
 array = [[2,text],[5,text],[1,text]]; array.sort(function(a,b){return a[0] < b[0]}) 
+11
source
 array = [[2,text],[5,text],[1,text]]; array.sort(function(a,b){return a[0] - b[0]}) 

sort function
if the function returns

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

Additional information at source .

0
source

Source: https://habr.com/ru/post/1485600/


All Articles