-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.

4

2 Answers 2

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()

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

what if there will be S20_ and S3_ items?
I have tried using .sort() and it doesn't work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.