Sort a array of objects lexicographically based on a nested value
Using Javascript, I would like to know how to sort lexicographically a array of objects based on a string value in each object.
Consider:
[ { "name" : "bob", "count" : true "birthday" : 1972 }, { "name" : "jill", "count" : false "birthday" : 1922 }, { "name" : "Gerald", "count" : true "birthday" : 1920 } ]
How can I sort the array alphabetically by name? The name values are usernames, so I would like to maintain the letter casing.
Answer
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…