【问题标题】:how to sort array of objects in javascript如何在javascript中对对象数组进行排序
【发布时间】:2016-03-09 08:21:55
【问题描述】:

我想要下面由bayid显示的排序数组

Array 是数组名

[
 Object { bayid="35",  status=0},
 Object { bayid="1",  status=0},
 Object { bayid="37",  status=0}
]

Array.sort(function(a,b){return b.bayid >a.bayid})

我不确定这个函数返回什么,但我想编写一个返回排序数组的函数,如下所示

[
 Object { bayid="37",  status=0},
 Object { bayid="35",  status=0},
 Object { bayid="1",  status=0}
]

请帮忙

【问题讨论】:

标签: javascript arrays sorting object


【解决方案1】:

    var objArray = [{ bayid:"35",  status:0},{ bayid:"1",  status:0}, { bayid:"37",  status:0}];

    function compare(a,b) {
    
      if (a.bayid < b.bayid )
        return 1;
      else if (a.bayid > b.bayid)
        return -1;
      else 
        return 0;
    }
    
    console.log(objArray.sort(compare));

【讨论】:

    【解决方案2】:

    原始代码和一些解决方案的问题是它们错误地 sort by string value: b.bayid &gt; a.bayid

    这似乎可以正常工作,直到我们将最后一个元素设置为bayid="100" 并发现它返回"35" &gt; "100" = true。数组排序不正确。

    要修复此错误,我们可以使用parseInt(a.bayid) 或简单地在它前面加上一个加号,如 (+a.bayid),以按数字而非字符串值排序。现在在阵列土地上一切都很开心。

    运行下面的 sn-p 来查看两种排序方法的结果。

    var _a = [
      
        {bayid: "35",  status: 0 },
        {bayid: "1",   status: 0 },
        {bayid: "100", status: 0 }
    
    ].sort(function(a, b) { 
      return b.bayid > a.bayid;   // <== to compare string values
    });
    
    print('Test 1: Sort by string', _a );
    
    
    _a = [
      
        {bayid: "35",  status: 0 },
        {bayid: "1",   status: 0 },
        {bayid: "100", status: 0 }
    
    ].sort(function(a, b) { 
      return +b.bayid > +a.bayid;   // <== to compare numeric values
    });
    
    print('Test 2: Sort by number', _a );
    
    
    function print( s, o ) {
      window.stdout.innerHTML += s + '\n' + JSON.stringify(o, false, '  ') + '\n\n';
    }
    Scroll down to view result:<br>
    <xmp id="stdout"></xmp>

    【讨论】:

      【解决方案3】:

      您的代码可以正常工作。 阅读更多关于 .sort 函数here

          var arr = [{ bayid:"35",  status:0}, { bayid:"1",  status:0}, { bayid:"37",  status:0}];
      
          var sortedArr = arr.sort(function(a,b) {return b.bayid > a.bayid});
      
          console.log(sortedArr);

      【讨论】:

        【解决方案4】:

        这些 JSON 项的语法在您的代码中似乎有些混乱。 试试这个

        var _a = [
        { bayid : 35,  status : 0},
        { bayid : 1,  status : 0},
        { bayid : 37,  status : 0}
        ] ;
        
        _a.sort(function(a,b){return b.bayid >a.bayid}) ;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-01-08
          • 2012-06-22
          • 2012-05-02
          • 2010-11-28
          • 2022-06-17
          • 1970-01-01
          • 2021-08-13
          相关资源
          最近更新 更多