Filtering a Typeahead Bloodhound Dataset

For a recent bug ticket at work I had to figure out how to prevent a selected item from appearing again in a Twitter Typeahead Bloodhound suggestion set.

It turns out I wasn’t the only one trying to do this — there’re a couple of StackOverflow questions and a Typeahead bug report. From the latter you can see that removing an item directly from a dataset is not yet supported — but that doesn’t mean you can’t currently achieve the same thing.

The key is to track which data has been selected indpendently of the Bloodhound dataset and not to use Bloodhound#ttAdapater() as your typeahead source. The ttAdapter method is simply a wrapper for Bloodhound#get(query, cb) — so instead of it, call get(query, cb) directly with a custom callback that checks each suggestion against the current selections.

Here is a JSFiddle illustrating this in action. Type “dog” and select it — you’ll notice that when you type “d” again, “dog“ is not part of the suggestion set.

It’s easy enough to implement some kind of de-selection functionality as well — all you’d need to do is remove the item from the selected array, since the Bloodhound dataset is never actually modified. Try something like

selected = $.grep(selected, function(objVal) {
    return objVal != deselectedVal;
});

Then your previously selected item will automatically appear in your Bloodhound suggestions again.