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?
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
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.
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
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) } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With