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?
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?
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) } );
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".