Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by decimal then by string - Javascript

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.

like image 835
Ediste Dela Cruz Avatar asked Jan 02 '26 08:01

Ediste Dela Cruz


2 Answers

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"] 
like image 136
Denys Séguret Avatar answered Jan 03 '26 21:01

Denys Séguret


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;
})
like image 35
lordvlad Avatar answered Jan 03 '26 20:01

lordvlad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!