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?
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?
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;
}
});
You can just subtract too:
myArray.sort( function( x, y ) { return x[0] - y[0]; } )
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 :)