I need to sort an array of this format, using plain old Javascript.
var arr = ["0.01 BASIC", "0.01 SEF", "0.015 BASIC"];
What I need is for the array to be sorted first by decimal then by string and produce an output just like below;
arr = ["0.01 BASIC", "0.015 BASIC", "0.01 SEF"];
I cannot use jquery in performing the sort. Just plain good old Javascript.
You can do this :
arr.sort(function(a,b){
var at = a.split(' '), bt = b.split(' ');
if (at[1]!=bt[1]) return at[1]>bt[1] ? 1 : -1;
return parseFloat(at[0])-parseFloat(bt[0]);
});
If you want to sort a very big array, it might be faster to cache the keys. But it probably doesn't matter for most arrays.
Example :
["0.01 BASIC", "0.01 SEF", "0.015 BASIC", "0.2 BASIC", "0.001 SEF", "0.2 AAA"]
->
["0.2 AAA", "0.01 BASIC", "0.015 BASIC", "0.2 BASIC", "0.001 SEF", "0.01 SEF"]
two consecutive sorts will work:
arr.sort(function(a,b){
// sort by words first
return a.match(/[a-z]+/i).join("")<b.match(/[a-z]+/i).join()?-1:1;
}).sort(function(a,b){
// sort by numbers next, but only if the words are equal
return a.match(/[a-z]+/i).join("")!==b.match(/[a-z]+/i).join("")?0:parseInt(a)<parseInt(b)?-1:1;
})
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