Sort type sentences with exact input up

I use Twitter typeahead.js 0.10.5 as a suggestion mechanism. It works great, with one exception, I cannot sort the list of offers the way I want.

As an example:

var data =[{"id":1,"value":"no need"}, {"id":2,"value":"there is no need"}, {"id":3,"value":"in the need of"}, {"id":4,"value":"all I need"}, {"id":5,"value":"need"}, {"id":6,"value":"needs"}, {"id":7,"value":"all he needs"}, {"id":8,"value":"he needs"}, {"id":9,"value":"they need"}, {"id":10,"value":"you need"}] var suggestion = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, local: data, limit: 20 }); suggestion.initialize(); $('.typeahead').typeahead({ hint: true, autoselect: true, highlight: true, minLength: 1 }, { name: 'suggestion', displayKey: 'value', source: suggestion.ttAdapter(), templates: { empty: [ '<div class="empty-message">', 'no suggestion in this map', '</div>' ].join('\n'), suggestion: Handlebars.compile('<p><span class="suggestion-text">{{value}}</span></p>') } 

When I type โ€œneed,โ€ I get sentences ordered by position in the array, but I would like it to be ordered by input, which means that the order should be โ€œneededโ€, โ€œneededโ€, โ€œall I need need "... When typing" he "it should be" need "," all that he needs "," all that I need ", etc.

I know that Bloodhound has a sorter option, but I donโ€™t know how to use it in this particular situation.

+8
sorting bloodhound
source share
2 answers

You want something in this direction. This will move the exact match up. You want to continue modifying the sorter code to handle a string flag, a space, and how you want to handle not perfect, but close matches. This should help you get started.

  var suggestion = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, local: data, limit: 20, sorter:function(a, b) { //get input text var InputString= $(Selector).val(); //move exact matches to top if(InputString==a.value){ return -1;} if(InputString==b.value){return 1;} //close match without case matching if(InputString.toLowerCase() ==a.value.toLowerCase()){ return -1;} if(InputString.toLowerCase()==b.value.toLowerCase()){return 1;} if( (InputString!=a.value) && (InputString!=b.value)){ if (a.value < b.value) { return -1; } else if (a.value > b.value) { return 1; } else return 0; } }, }); 
+12
source share

To sort all matches by proximity to the input, you can select Levenshtein distance a and b . I just implemented this with fast-levenshtein and it works and works great.

  sorter: function(a, b) { var input_string = $(selector).val(); return levenshtein.get(a.key, input_string) - levenshtein.get(b.key, input_string); } 
+7
source share

All Articles