Jon Garrido Martin GIS Developer

GIS Developer Freelance

How to sort an array of objects in javaScript

By jongarrido | September 8, 2015 | 0 Comment

I ‘ve found this code very useful, I hope you’ll find useful too…you can get sorted array of objects based on any of the properties in the objects..

 

For a fixed field we can go through this code…

function (a,b)
{
if (a.sortfield< b.sortfield)
return -1;
if (a.sortfield > b.sortfield)
return 1;
return 0;
}

And now sort our array…

array.sort(compare);

To use this code for a varible sort-field…

function getCompareFunction(sortfield)
{
var compare = function (a,b)
{
if (a[sortfield] < b[sortfield])
return -1;
if (a[sortfield] > b[sortfield])
return 1;
return 0;
}
return compare
}

And now sort our array…

array.sort(getCompareFunction("myfield")); //the array will be sorted by myfield field....

Any feedback it’s welecome!!!

TAGS

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *