Sorting an array based on an attribute of an object - Javascript

I have an array of objects called canvasObjects .

Each object has an attribute z .

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

+7
source share
3 answers

You just need to pass the sort function to the comparator

 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 POST

+9
source

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

 canvasObjects.sort(function(a,b) { return parseFloat(az) - parseFloat(bz) } ); 
+1
source

Sending an anonymous function to the sort method, which returns the subtraction of the "z" property

 var arr = [{z:2},{z:4},{z:5},{z:1},{z:3}]; arr.sort(function(a,b) {return az - bz}); 

above puts the numbers in z in the order of 1,2,3,4,5. To reverse the order, return "bz - az".

0
source

All Articles