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?
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?
Share Improve this question asked Apr 29, 2013 at 13:33 Federico CapelloFederico Capello 1,1183 gold badges12 silver badges21 bronze badges 1- Mix Sorting objects in an array by a field value in JavaScript with sort a javascript array of numbers (didn't found the exact dupe of this) – Bergi Commented Apr 29, 2013 at 13:38
2 Answers
Reset to default 6Try this
myArray.sort(function(a,b) {return a[0]-b[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./javatutors/arraysort.shtml
The function specifies whether the numbers should be sorted ascending or descending.
Here you have more examples http://www.w3schools./jsref/jsref_sort.asp