Backbone is great but I continually found the default sorting method limited due to the following:
Disc 1, Disc 2, … Disc 10
would become Disc 1, Disc 10, Disc 2
With the help of Jim Palmer's naturalSort.js, I was able to integrate natrual sorting into Backbone.Collection
.
Backbone collections are automatically sorted and now, by simply adding sortType:"natural"
, your collections can be sorted naturally.
// unsorted data
var data = [
{label: 'Disc 1'},
{label: 'Disc 2'},
{label: 'Disc 10'},
{label: 'Disc 3'},
{label: 'Disc 11'}
];
var Collection = Backbone.Collection.extend({
comparator: function(m){
return m.get('label');
}
});
var NatrualCollection = Backbone.Collection.extend({
sortType: 'natural',
comparator: function(m){
return m.get('label');
}
});
var coll = new Collection(data);
var collNat = new NatrualCollection(data);
console.log('Not sorted naturally', coll.pluck('label'));
console.log('Sorted naturall', collNat.pluck('label'));
An underscore.js method is also available
var sorted = _.sortByNat(data, function(m){ return m.label });
console.log(_.pluck(sorted, 'label'));
Lastly, natural sort can be called directly on an Array
["Disc 1", "Disc 2", "Disc 10", "Disc 3", "Disc 11"].sortNat();