Algolia instantsearch.js: how to display results in random order?

I use Algolia instantsearch.js to show candidates for elections (here: https://laprimaire.org/candidats/ ). I would like the initial run of candidates to be random, so that each candidate gets more or less the same visibility.

I read in this answer that this is not a feature of Algolia, but that it should be possible to do it anyway with a little trick js: Is it possible to sort randomly and query in the field if it exists?

The problem is that I am using instantsearch.js and I cannot find how to implement the above search function in case of instantsearch.js.

The documentation shows that instantsearch can be initialized using the search function, which receives an auxiliary parameter as a parameter: https://community.algolia.com/instantsearch.js/documentation/#initialization

However, he did not find documentation about this assistant and how to manipulate it so that I could apply a random function to the search results.

Any help would be greatly appreciated! Thank you very much

Thibauld

+5
source share
1 answer

The widget widget allows you more control over how to display the list of views through transformData.allItems and templates.allItems parameters .

Using the shuffle method of this question How to shuffle an array? :

 function shuffle (o){ for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } 

You can simply do:

 search.addWidget( instantsearch.widgets.hits({ // Your other options transformData: { allItems: function (content) { return { hits: shuffle(content.hits) }; } }, templates: { empty: 'No results', allItems: '{{#hits}}<your previous templates.hit value>{{/hits}}' } }) ); 

The {{#hits}}{{/hits}} template is just some Hogan.js logic for looping each of your hits.

+6
source

Source: https://habr.com/ru/post/1247535/


All Articles