Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array by first item in subarray

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!

like image 204
zdebruine Avatar asked Jun 11 '13 11:06

zdebruine


2 Answers

array = [[2,text],[5,text],[1,text]];
array.sort(function(a,b){return a[0] < b[0]})
like image 140
Hilmi Avatar answered Sep 19 '22 00:09

Hilmi


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.

like image 24
Ninad Nehete Avatar answered Sep 19 '22 00:09

Ninad Nehete