22

I have an array of objects called canvasObjects.

Each object has an attribute called z.

I want to sort this array based on objects z. How do I do this using the sort() method?

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225

3 Answers3

30

You just need to pass in a comparator to the sort function

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

Community
  • 1
  • 1
Lee McGrath
  • 321
  • 2
  • 2
7

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) } );
Mironline
  • 2,755
  • 7
  • 35
  • 61
Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
2

Send anonymous function to the sort method which returns a subtraction of the property "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".

nsgulliver
  • 12,655
  • 23
  • 43
  • 64