-3

I wanna sort an array like below by the numeric values in the first column.

myArray = [
   [5,"Titel"],[3,"Titel"],[1,"Titel"],[2,"Titel"],[4,"Titel"]
];

How can I do this?

sln
  • 83
  • 1
  • 2
  • 9
  • 1
    please try searching before asking questsions like this...there are 100's of examples here and other web resources – charlietfl Jan 18 '16 at 05:09

3 Answers3

3

The sort method of array takes a custom comparator method as an optional parameter:

myArray.sort(function(a, b) {
  if(a[0] > b[0]) {
    return 1;
  } else {
    return -1;
  }
});
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
2

You can just subtract too:

myArray.sort( function( x, y ) { return x[0] - y[0]; } )
George Houpis
  • 1,729
  • 1
  • 9
  • 5
-2

By using Jquery sort() function you can achieve this.

Here is the Fiddle for your question.

myArray=myArray.sort();

Edit

Rightly pointed out the default sort function wont work as we want to thus solution will be as George Houpis pointed out.

myArray.sort( function( x, y ) { return x[0] - y[0]; } )

-Help :)

Help
  • 1,156
  • 7
  • 11
  • Put this in array also `[10,"Titel"], [20,"Titel"]`. Will see that it doesn't work as expected. https://jsfiddle.net/q03q8a8a/1/ – charlietfl Jan 18 '16 at 05:07