JON GARRIDO GIS EXPERT - DESARROLLADOR GIS

DESARROLLADOR GIS FREELANCE

How to sort an array of objects in javaScript

By jongarrido | septiembre 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

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *