Using JavaScript, I would like to know how to sort lexicographically an 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.
Java Program to Sort Elements in Lexicographical Order (Dictionary Order) Sorting a string array in Lexicographical Order (Dictionary Order) using two approaches: By using any sorting technique to sort array elements. By using sort() function present in Arrays class in util package in java.
To sort a string array in JavaScript, call sort() method on this string array. sort() method sorts the array in-place and also returns the sorted array, where the strings are sorted lexicographically in ascending order. Since, the sort operation happens in-place, the order of the elements in input array are modified.
Defining Lexicographical Order Thus, lexicographical order is a way for formalizing word order where the order of the underlying symbols is given. In programming, lexicographical order is popularly known as Dictionary order and is used to sort a string array, compare two strings, or sorting array elements.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With