Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array based on Object Attribute - Javascript [duplicate]

Tags:

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?

like image 226
Philip Kirkbride Avatar asked Mar 24 '13 00:03

Philip Kirkbride


People also ask

How do you sort an array by object value?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort an array of objects by string?

To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.


2 Answers

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

like image 176
Lee McGrath Avatar answered Sep 22 '22 17:09

Lee McGrath


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) } );
like image 42
Philip Kirkbride Avatar answered Sep 22 '22 17:09

Philip Kirkbride