Sort an array in ascending order based on ints, not strings

I have an array with this structure:

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

I would like to sort the array according to purpose. Unfortunately, when I call .sort () in myArray, it returns me an array sorted by rows. How can i solve this?

+5
source share
2 answers

try it

myArray.sort(function(a,b) {return a[0]-b[0]})
+6
source

To perform numerical sorting, you must pass the function as an argument when calling the sorting 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 this at http://www.javascriptkit.com/javatutors/arraysort.shtml

The function determines whether the numbers should be sorted in ascending or descending order.

http://www.w3schools.com/jsref/jsref_sort.asp

0

All Articles