Search⌘ K

Solution: Sorting a Collection

Understand how to sort collections in Marionette by applying sortBy and comparator functions. Learn to implement flexible sorting logic, including sorting by multiple attributes, to manage and display models effectively in your JavaScript apps.

We can use either a sortBy function or a sort comparator function that expects two arguments.

Solution 1: Using the sortBy function

We create the following function, which has been highlighted in the code provided below:

<script type="text/javascript">
    var ContactManager = new Marionette.Application();

    ContactManager.Contact = Backbone.Model.extend({});

    ContactManager.ContactCollection = Backbone.Collection.extend({
        model: ContactManager.Contact,
        comparator: function(contact) {
            return contact.get("firstName") + " " + contact.get("lastName");
        }
    });

    ContactManager.ContactItemView = Marionette.ItemView.extend({
        tagName: "li",
        template: "#contact-list-item"
    });

    ContactManager.ContactsView = Marionette.CollectionView.extend({
        tagName: "ul",
        childView: ContactManager.ContactItemView
    });

    ContactManager.on("before:start", function(){
    var RegionContainer = Marionette.LayoutView.extend({
        el: "#app-container",

        regions: {
            main: "#main-region"
        } 
    });

    ContactManager.regions = new RegionContainer(); 
    });

    ContactManager.on("start", function(){
        var contacts = new ContactManager.ContactCollection([
        {
            firstName: "Alice",
            lastName: "Tampen"
        }, 
        { 
            firstName: "Bob",
            lastName: "Brigham"
        },  
        {
            firstName: "Alice",
            lastName: "Artsy"
        }, 
        {
            firstName: "Alice",
            lastName: "Arten"
        },
        {
            firstName: "Charlie",
            lastName: "Campbell"
        }, 
        {
            firstName: "Alice",
            lastName: "Smith"
        },
        ]);

        var contactsListView = new ContactManager.ContactsView({
        collection: contacts
        });

        ContactManager.regions.main.show(contactsListView);
    });
    
    ContactManager.start(); 
</script>
Sorting with the sortBy functon

As you can see, the comparator ...