基于对象属性对数组进行排序 - Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15593850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort Array based on Object Attribute - Javascript
提问by Philip Kirkbride
I have an array of objects called canvasObjects
.
我有一个名为canvasObjects
.
Each object has an attribute called z
.
每个对象都有一个名为 的属性z
。
I want to sort this array based on objects z
. How do I do this using the sort()
method?
我想根据对象对这个数组进行排序z
。我如何使用该sort()
方法执行此操作?
回答by Lee McGrath
You just need to pass in a comparator to the sort function
您只需要将比较器传递给 sort 函数
function compare(a,b) {
if (a.attr < b.attr)
return -1;
if (a.attr > b.attr)
return 1;
return 0;
}
canvasObjects.sort(compare);
Or inline
或内联
canvasObjects.sort(function(a,b) {return (a.attr > b.attr) ? 1 : ((b.attr > a.attr) ? -1 : 0);} );
See this POST
看到这个帖子
回答by Philip Kirkbride
Tried other answers posted here but then I found the following to work best.
尝试了此处发布的其他答案,但后来我发现以下方法效果最佳。
Ascending:
升序:
canvasObjects.sort(function(a,b) { return parseFloat(a.z) - parseFloat(b.z) } );
Descending:
降序:
canvasObjects.sort(function(a,b) { return parseFloat(b.z) - parseFloat(a.z) } );
回答by smileylauri
Send anonymous function to the sort method which returns a subtraction of the property "z"
将匿名函数发送到 sort 方法,该方法返回属性“z”的减法
var arr = [{z:2},{z:4},{z:5},{z:1},{z:3}];
arr.sort(function(a,b) {return a.z - b.z});
above puts numbers in z to order 1,2,3,4,5. To reverse the order make it return "b.z - a.z".
上面将 z 中的数字按 1,2,3,4,5 顺序排列。颠倒顺序使其返回“bz - az”。