基于对象属性排序数组 - Javascript [复制]

时间:2021-11-23 22:31:22

This question already has an answer here:

这个问题在这里已有答案:

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()方法执行此操作?

3 个解决方案

#1


12  

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

看到这个POST

#2


3  

Tried other answers posted here but the I found the following to work best.

尝试在这里发布的其他答案,但我发现以下工作最好。

canvasObjects.sort(function(a,b) { return parseFloat(a.z) - parseFloat(b.z) } );

#3


0  

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。要颠倒顺序,请返回“b.z - a.z”。

#1


12  

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

看到这个POST

#2


3  

Tried other answers posted here but the I found the following to work best.

尝试在这里发布的其他答案,但我发现以下工作最好。

canvasObjects.sort(function(a,b) { return parseFloat(a.z) - parseFloat(b.z) } );

#3


0  

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。要颠倒顺序,请返回“b.z - a.z”。