-1

I have an array of values that look like this:

var myArr = ["S1_FORM", "S3_FORM", "S2_FORM", "S2_2_FORM"];

I need to sort them from lowest to highest.

The way I would like this array to be is like this:

["S1_FORM", "S2_FORM", "S2_2_FORM", "S3_FORM"]

Basically these numbers should be read like: 1, 2, 2.2, 3

How could I achieve this?

I have tried using .sort() but it returns:

["S1_FORM", "S2_2_FORM", "S2_FORM", "S3_FORM"]

notice "2_2" comes before "2_". It shouldn't.

Dylan Cross
  • 5,918
  • 22
  • 77
  • 118

2 Answers2

3
var myArr = ["S1_FORM", "S3_FORM", "S2_FORM", "S2_2_FORM"];

var extractNumber = function(str) {
    var m = str.match(/^S(\d+)_(?:(\d+)_)?/);
    return parseFloat(m[1] + '.' + m[2])
};

myArr.sort(function(a, b) {
    return extractNumber(a) - extractNumber(b);
});

console.log(myArr);

http://jsfiddle.net/LDphK/

So you're extracting a number using trivial regular expression and then sort it using Array.prototype.sort()

zerkms
  • 249,484
  • 69
  • 436
  • 539
0
var myArr = ["S1_FORM", "S3_FORM", "S2_FORM", "S2_2_FORM"];
 myArr.sort(); 

If you need another sorting logic, use jQuery. This is vanilla JavaScript solution

Jurion
  • 1,230
  • 11
  • 18