1

I have an array like this in JS:

var a = ["1", "2", "1_10", "1_22", "2_12", "3", "14", "1_15", "3_31", "14_25", "2_18"];

and I need to sort it, in order to look like this:

["1", "1_10", "1_15", "1_22", "2", "2_12", "2_18", "3", "3_31", "14", "14_25"];

I tried using a function like the one in this fiddle http://jsfiddle.net/r7vQP/ but I am getting a wrong answer (["1", "14", "14_25", "1_10", "1_15", "1_22", "2", "2_12", "2_18", "3", "3_31"]).

0

4 Answers 4

1

Try this:

var b = a;
for (var i = 0; i < b.length; i++) {
    b[i] = b[i].replace('_', '.');
}


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


for (var y = 0; y < b.length; y++) {
    a[y] = b[y].replace('.', '_');
}
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Nice - the trick is to keep the values as strings so you don't loose the 0 off the "1.10" but temporarily convert it to float during the sort.
@Matt Thanks! However I don't quite understand what you meant, I ran the function and the zero in for example 1_10 did not get lost after the sorting.
Yes, that's why I gave it a +1 :). Compare to one of the other answers present which do lose the 0, as well as early versions of my own answer.
1
function numericSort(a, b) {
    return a - b;
}

a.map(function (e) {
    return parseFloat(e.replace("_", "."));
})
.sort(numericSort)
.map(function (e) {
    return e.toString().replace(".", "_");
})

Comments

1
var a = ["1", "2", "1_10", "1_22", "2_12", "3", "14", "1_15", "3_31", "14_25", "2_18"];
function sortByFloat (a,b)
{
a=parseFloat (a.replace ("_",".")); b=parseFloat (b.replace ("_",".")); if (a<b) return -1; if (a>b) return 1; if (a==b) return 0; } a.sort (sortByFloat);

return a-b would be faster instead of the three if conditions

Comments

0
function to_dot(s) { return s.replace('_','.') }
function from_dot(n) { return n.replace('.','_') }

a.map(to_dot).sort(function(a,b){return a-b}).map(from_dot)

["1", "1_10", "1_15", "1_22", "2", "2_12", "2_18", "3", "3_31", "14", "14_25"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.