sort array with integer strings type in jQuery

后端 未结 5 1340
后悔当初
后悔当初 2020-12-10 19:25

I have a array of integers of type string.

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

output

>>> var a = [\'2         


        
相关标签:
5条回答
  • 2020-12-10 19:50

    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;
    });
    
    0 讨论(0)
  • 2020-12-10 19:55

    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"]
    
    0 讨论(0)
  • 2020-12-10 19:56

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

    Mozilla sort Method

    0 讨论(0)
  • 2020-12-10 20:03

    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);
    
    0 讨论(0)
  • 2020-12-10 20:08

    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"]
    
    0 讨论(0)
提交回复
热议问题