What is the best way to organize search results in typeahead/bloodhound?

I am currently working with typeahead.js version 0.11.1 and attempting to customize the sorting of results retrieved from a remote source. Despite implementing code that should allow me to override the default sort function of bloodhound, my custom sort function never seems to be triggered. The same issue applies to the identify function.

Below is the code I have been using:

    var bloodhoundSearchEngine = new Bloodhound({
    // we do not need any tokenization cause this will be done on the server
    datumTokenizer : function(d) {
        return d;
    },
    queryTokenizer : function(q) {
        return q;
    },
    sorter : function(itemA, itemB) {
        console.log(itemA);
        if (itemA.count < itemB.count) {
            return -1;
        } else if (itemA.count > itemB.count) {
            return 1;
        } else
            return 0;
    },
    identify : function(item) {
        console.log(itemA);
        return item.value;
    },
    remote : {
        url : '/suggest/?term=%term',
        wildcard : '%term',
        transform : function(response) {
            return $.map(response.suggestItems, function(item) {
                return {
                    value : item.value,
                    count : item.count
                };
            });
        },
        rateLimitBy : 'debounce',
        rateLimitWait : 300
    }
});

$('#typeaheadinput .typeahead')
        .typeahead(
                {
                    hint : true,
                    highlight : true,
                    minLength : 1
                },
                {
                    name : 'existing-names',
                    display : 'value',
                    limit : 20,
                    source : bloodhoundSearchEngine.ttAdapter()
                });

Does anyone have suggestions or guidance on how to resolve this issue?

Answer №1

I decided to customize the sorting process by implementing a unique transform function for handling suggestions retrieved from the server. This led me to include a call to the sorter within my transform function, resulting in successful execution of the following code:

var customizedSearchEngine = new CustomBloodhound({
    datumTokenizer : function(d) {
        return d;
    },
    queryTokenizer : function(q) {
        return q;
    },
    sorter : function(itemA, itemB) {
        console.log(itemA);
        if (itemA.count < itemB.count) {
            return -1;
        } else if (itemA.count > itemB.count) {
            return 1;
        } else
            return 0;
    },
    identify : function(item) {
        console.log(itemA);
        return item.value;
    },
    remote : {
        url : '/customsuggest/?term=%term',
        wildcard : '%term',
        transform : function(response) {
            return $.map(customizedSearchEngine.sorter(response.suggestItems), function(item) {
                return {
                    value : item.value,
                    count : item.count
                };
            });
        },
        rateLimitBy : 'debounce',
        rateLimitWait : 300
    }
});

$('#custominput .autocomplete')
        .typeahead(
                {
                    hint : true,
                    highlight : true,
                    minLength : 1
                },
                {
                    name : 'unique-names',
                    display : 'value',
                    limit : 20,
                    source : customizedSearchEngine.ttAdapter()
                });

Answer №2

After encountering issues with the sorted function not being called, I sought help from René and was able to resolve the issue.

var blood = new Bloodhound({
sorter: function(a, b) {
    var input_string = $(selector).val();
    distance = Levenshtein.get(a.name, input_string) - Levenshtein.get(b.name, input_string)
    return distance;
},
remote: {
    transform : function(response) {
        return blood.sorter(response)
    },
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: Invalid credentials for Twitter API authentication

My attempts to post a tweet seem to be failing for some reason. I suspect that the issue might be related to the signature string, but from following Twitter's instructions on signing requests, everything appears correct. Here is the code snippet I ...

Having difficulties retrieving a binary file using aws-sdk

I'm currently in the process of transitioning my server from knox to the official aws-sdk. However, I've encountered some discrepancies with the final outcomes. When using aws-sdk, I employ the getObject method to retrieve a file as shown below: ...

Utilizing custom filters to navigate through nested ng-repeats

My goal is to achieve a specific behavior by using custom filters. I am working on creating a unified search bar that will display entire group names with all failing students, as well as group names with only the matching students. If you want to see the ...

Utilizing Express Session with Vue CLI in a Node.js Environment

Developing a nodejs backend for my Vue application has brought up a challenge regarding user sessions and database operations. I initially tried using express-session, but the sessions appeared as undefined in subsequent requests. How can I address this is ...

Sophisticated method for implementing dynamic components with props in Vue

In a specific scenario, I am using an API to output all the content for my Page, including its structure. To provide context, imagine a CMS with a page builder feature where authors can place components via drag and drop to create pages, which are then del ...

Is it possible to validate without having to refresh the page?

I am brand new to coding and I have a login form on my index.php page. <form action="login.php" method="post" name="form1"> <div class="form-group"> <div class="form-label-group"> <input type="text" id="inputEm ...

What is the best way to store the outcome of a promise in a variable within a TypeScript constructor?

Is it possible to store the result of a promise in a variable within the constructor using Typescript? I'm working with AdonisJS to retrieve data from the database, but the process involves using promises. How do I assign the result to a variable? T ...

Disabling the child element from triggering the parent element's onclick function, while still allowing it to respond to its own content

My list elements have onclick-functions that change the display of each element and its child div, moving them to the top of the list. Clicking again reverses this effect. The issue arises because the child div contains search fields, clickable pictures, ...

Can Protractor be used to test flow without incorporating the login process?

Is there a way to test the flow using Protractor that occurs after the login page without actually having to go through the login process? ...

Utilize JavaScript to showcase a message based on the user's time measured in seconds

With a collection of 5000 text strings, each assigned a time value ranging from 0 to 86400 seconds... I am looking to determine the user's current time and display the corresponding text string. Subsequently, as the user's time changes, I aim to ...

Angular directives do not support the compilation of HTML code within them

angular.module("vtApp.directives"). directive('multirangeslider', function ($compile) { return { restrict: 'E', replace: true, link: function (scope, element, attrs) { var variances, values, optio ...

Browsing through the highcharts visualization graph

My current project involves developing a hybrid app using the phonegap framework, and I have decided to incorporate graphs using the highcharts library. However, I am facing an issue where I am unable to scroll after interacting with the chart within the ...

Unable to access a PHP file within a JavaScript loop

In my HTML document, there is a button with an onclick method inside a JavaScript <script> tag. When this button is clicked, it triggers the deleteRow function, which is responsible for removing a row from a table on the page. Within the deleteRow f ...

How can I extract and display a particular attribute from an object in a list retrieved through AJAX?

I am currently working on an AJAX call that retrieves a list of objects in JSON format from a database. These objects are then used in an autocomplete text input. However, my challenge is to display only the NAME attribute of each object in the list. $(fu ...

Error encountered in MySQL and NodeJS: Unable to add new query after invoking quit with transactions

While working on implementing MySQL for NodeJS and Restify, I encountered a flawless experience with queries. However, when attempting to utilize data updating functionality through transactions, I faced the error message: Error: Cannot enqueue Query after ...

Execute a POST request using Puppeteer

Currently, I am experimenting with JS+Puppeteer to create a script for adding items to the cart on a website. Due to heavy traffic, the website often crashes, so I want to bypass traditional clicking methods and instead send item information directly to th ...

What is the correct way to iterate through a list of images fetched with getStaticProps and display them within the same component?

What is the proper way to map a list of images returned using getStaticProps? I had successfully implemented this by passing a prop to the gallery component in another page. However, I now want to consolidate all the getStaticProps code within the gallery ...

What is the best way to access the methods in the "parent" class?

I am facing a situation where I have an object with fieldsCreators that hold creator methods for each field. The dilemma is how to call the creator method inside fieldsCreators as shown below: var obj={ creator:function(ch) { .... .. ...

Is {{@index}} an even or odd number in Handlebars: A Step-by-Step Guide

I'm currently cycling through an array, and I'd like to adjust the background color of the div based on whether the current index is odd or even. Unfortunately, when I try to use {{@index}} within an if statement in Handlebars, like so: {{#each ...

Using Python within HTML with Python integration

df2 = pd.DataFrame(np.random.randn(5, 10)).to_html() myPage = """ <html> <body> <h2> Programming Challenge </h2> <form action="/execute" method="get"> <sele ...