[英]how to sort array of objects in javascript
我想要排序数组,如下所示 bayid
数组是数组名称
[
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}
]
怎么做,请帮忙
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));
原始代码和一些解决方案的问题是它们按字符串值错误地排序: b.bayid > a.bayid
这似乎工作正常,直到我们将最后一个元素设置为 bayid="100" 并发现它返回"35" > "100" = true
。 数组排序不正确。
为了修复这个错误,我们可以使用parseInt (a.bayid) 或者简单地在它前面加上一个像 (+a.bayid) 这样的加号来按数字而不是字符串值排序。 而现在阵地一切都是幸福的。
运行下面的代码片段以查看两种排序方法的结果。
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>
这些 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}) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.