4

I have a array of integers of type string.

var a = ['200','1','40','0','3'];

output

>>> var a = ['200','1','40','0','3'];
console.log(a.sort());
["0", "1", "200", "3", "40"]

I'll also have a mixed type array. e.g.

var c = ['200','1','40','apple','orange'];

output

>>> var c = ['200','1','40','apple','orange']; console.log(c.sort());
["1", "200", "40", "apple", "orange"]

==================================================
The integers of string type gets unsorted.

5
  • 2
    How do you need to sort it? Numbers first in numeric order, then alphas in alphabetical? Commented Sep 1, 2013 at 3:28
  • So, what do you need? Commented Sep 1, 2013 at 3:33
  • @YuriyGalanter, numbers first then alphabetically.... Commented Sep 1, 2013 at 3:35
  • 1
    @user1051068 Please update the question with expected output. Commented Sep 1, 2013 at 3:36
  • @user1051068 Try ['200','1','40','orange','apple'] and you will see that strings are sorted, too. Your example has already sorted strings. And "1", "200", "40" is a correct order. Commented Sep 1, 2013 at 3:42

5 Answers 5

18

As others said, you can write your own comparison function:

var arr = ["200", "1", "40", "cat", "apple"]
arr.sort(function(a,b) {
  if (isNaN(a) || isNaN(b)) {
    return a > b ? 1 : -1;
  }
  return a - b;
});

// ["1", "40", "200", "apple", "cat"]
Sign up to request clarification or add additional context in comments.

3 Comments

He added that after I finished :) Just updated mine, but I like your one liner
funny thing is that parseInt() is unnecesary (although it makes things clearer) :)
c = ['200','1','10','40','cba','abc']; Run the function ["200", "1", "10", "40", "cba", "abc"] No Luck
6

This should be what you're looking for

var c = ['200','1','40','cba','abc'];
c.sort(function(a, b) {
  if (isNaN(a) || isNaN(b)) {
    if (a > b) return 1;
    else return -1;
  }
  return a - b;
});
// ["1", "40", "200", "abc", "cba"]

3 Comments

If alphas don't need sorting
parseFloat does not accept a radix argument. More importantly, note that just using the - operator will cast the strings to numbers (and faster, too). In other words, just return a-b.
FAILS to sort if there is another integer of string type at last var data = ['88','331','11','46','4445', '200', 'a', '300']; alert(data.sort(function(a, b) { return parseFloat(a) - parseFloat(b); }) );
1

You need to write your own sort function.

a.sort(function(a,b)) {
    var intValA = parseInt(a, 10);
    var intValB = parseInt(b, 10);

    if (!isNaN(parseInt(a, 10))) && !isNaN(parseInt(b, 10)) {
        // we have two integers
        if (intValA > intValB)
            return 1;
        else if (intValA < intValB)
            return 0;
        return 1;
    }
    if (!isNaN(parseInt(a, 10)) && isNaN(parseInt(b, 10)))
        return 1;
    if (isNaN(parseInt(a, 10)) && !isNaN(parseInt(b, 10)))
        return -1;

    // a and b are not integers
    if (a > b)
        return 1;
    if (a < b)
        return -1;
    return 0;
});

4 Comments

Isn't IsNan applied after parseInt will always return false?
You can make this much less verbose with ternary operators instead of so many if statements, e.g. return a<b ? -1 : a>b ? 1 : 0
@Phrogz, yes, I was trying to make the return details easier to read, but you are right - it's longer than it needs to be.
also, if both are numbers you can just return the difference. If only one of them is a number then you can compare them as strings
0

Thanks all, though I dont know jQuery much, but from you guys examples, I summarized the code as follows which works as per my requirement

to be used in firebug

var data = ['10','2', 'apple', 'c' ,'1', '200', 'a'], temp;
temp = data.sort(function(a,b) {
         var an = +a;
         var bn = +b;
          
         if (!isNaN(an) && !isNaN(bn)) {
             return an - bn;
         } 
         return a<b ? -1 : a>b ? 1 : 0;
     }) ;
alert(temp);

3 Comments

just so you now +a coerces a to integer if it can, otherwise returns NaN. employing coersion Kazuki's answer can be the shortest one:arr.sort(function(a, b) { if (isNaN(a) || isNaN(b)) { return a > b ? 1 : -1; } return a - b; });
@soulcheck +a coerces to a Number, not an "integer".
@Kazuki, soulcheck did some modification which meets my criteria.. Thanks
-1

Most javascript implementations, as far as I know, provide a function you can pass in to provide your own custom sorting.

Mozilla sort Method

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.