5

I have an array with this structure:

myArray = [ [<number>, [<string>] ], [<number>, [<string>] ], ... ];

I'd like to sort the array according to the ints. Unfortunately, when I call .sort() on myArray it returns me an array sorted according to the strings. How could I solve this?

Federico Capello
  • 1,088
  • 3
  • 12
  • 21
  • Mix [Sorting objects in an array by a field value in JavaScript](http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript) with [sort a javascript array of numbers](http://stackoverflow.com/q/9438814/1048572) (didn't found the exact dupe of this) – Bergi Apr 29 '13 at 13:38

2 Answers2

6

Try this

myArray.sort(function(a,b) {return a[0]-b[0]})
Oktav
  • 2,143
  • 2
  • 20
  • 33
0

To perform a numeric sort, you must pass a function as an argument when calling the sort method.

var myarray=[[21,"aadfa"], [24,"ca"],[52,"aa"], [15,"ba"]]
myarray.sort(function(a,b){return a[0] - b[0]})

you can find more information about it on http://www.javascriptkit.com/javatutors/arraysort.shtml

The function specifies whether the numbers should be sorted ascending or descending.

Here you have more examples http://www.w3schools.com/jsref/jsref_sort.asp

Robert
  • 19,800
  • 5
  • 55
  • 85
  • I didn't see your answer, I've just noticed that it is multidimensional array and my answer was for one dimension array :) Also pointing to making function that gets two objects to compare is good advice and from that point it is not hard to figure out how to write comparing function. – Robert Apr 29 '13 at 13:43