Sorting Autocomplete Responses For Relevancy

Sorting the jQuery UI autocomplete response before it's rendered, based on some relevancy criteria.

by Adam Boduch

HTML

<div class="ui-widget">
    <label for="tags" class="ui-widget">Aw Nuts: </label>
    <input id="tags"/>
</div>

CSS

body {
    font-size: 0.8em;
}

JavaScript

// Our autocomplete data.
var nuts = [
    { label: "Acorn", timestamp: new Date( 2014, 0, 1 ) },
    { label: "Beech", timestamp: new Date( 2014, 1, 1 ) },
    { label: "Breadnut", timestamp: new Date( 2014, 2, 1 ) },
    { label: "Candlenut", timestamp: new Date( 2014, 3, 1 ) },
    { label: "Chestnut", timestamp: new Date( 2014, 4, 1 ) },
    { label: "Hazelnut", timestamp: new Date( 2014, 5, 1 ) }
];

$( "#tags" ).autocomplete({
    source: function( request, response ) {
        
        // Creates the filtered source array based on the current
        // search term using "nuts" as the input.
        var filtered = $.ui.autocomplete.filter(
            nuts,
            request.term
        );
        
        // Sorts the results based on some relevancy criteria, in
        // this case, the most recent "timestamp" property should
        // appear first.
        filtered.sort(function( a, b ) {
            return b.timestamp - a.timestamp;
        });
        
        response( filtered );
        
    }
});