I have an array of objects and I'm trying to sort them alphanumerically, take the following example:
var objs = {
'obj1': {'name': 'Object21'},
'obj2': {'name': 'Object140'},
'obj3': {'name': 'Object28'},
'obj4': {'name': 'Object251'}
};
When calling _.sortBy(objs, function(obj) { return obj.name; }
the output is:
- Object140
- Object21
- Object251
- Object28
How can I order this alphanumerically using Underscore? I know I could create a separate array using just the names but is there a better way of doing this using Underscore without creating an additional variable?
You will need to create your own iterator function and then use it, you can't actually do this with the iterator function, but you can get close to it:
"AnObject251" goes on the last place because of its length.
You need the Alphanum sorting algorithm and an elegant implementation in JavaScript:
I've managed to find a solution to this myself using Google :-) here's what I used for those that need this in future and it's actually called "Natural Sorting"
use by calling
_.sortByNat(objs, function(obj) { return obj.name; })