Sort a array of objects lexicographically based on a nested value

var obj = [...];

obj.sort(function(a,b){return a.name.localeCompare(b.name); });

Be aware that this will not take capitalisation into account (so it will order all names beginning with capitals before all those beginning with smalls, i.e. "Z" < "a"), so you might find it relevant to add a toUpperCase() in there.

You can make it more generic as well:

function sortFactory(prop) {
   return function(a,b){ return a[prop].localeCompare(b[prop]); };
}

obj.sort(sortFactory('name')); // sort by name property
obj.sort(sortFactory('surname')); // sort by surname property

And even more generic if you pass the comparator to the factory...


This will do it:

arr.sort(function(a, b) {
    return a.name.localeCompare(b.name);
});