Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a array of objects lexicographically based on a nested value

Tags:

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.

like image 289
Sachin Avatar asked Dec 16 '11 20:12

Sachin


People also ask

How do you sort an array Lexicographically?

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.

How do you sort Lexicographically in JavaScript?

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.

How do you sort Lexicographically?

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.


1 Answers

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...

like image 73
davin Avatar answered Oct 01 '22 13:10

davin