I am not using an associative array. I'm using 1d array like this,
array("1,a","5,b","2,c","8,d","6,f");
How can I sort this array?
The result should be,
array("1,a","2,c","5,b","6,f","8,d");
sort()
without a custom sorting function will sort it how you wish (lexicographically).
>>> ["1,a","5,b","2,c","8,d","6,f"].sort();
["1,a", "2,c", "5,b", "6,f", "8,d"]
Note that this will sort the original array. You can make a shallow copy with slice()
.
If any of your numbers are larger than 9
, and you want to sort it via the ordinal of the number, you will need a custom sorting function.
["1,a","5,b","2,c","8,d","6,f"].sort(function(a, b) {
return parseInt(a, 10) - parseInt(b, 10);
});
Use array.sort()
built-in JS function. Documentation here: http://www.w3schools.com/jsref/jsref_sort.asp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With