The problem here is that Select2, in the 4.0.0 release, separated the querying of results from the display of results. Because of this, the sorter
option which you would normally use to sort the results does not pass in the query that was made (which includes the search term).
So you are going to need to find a way to cache the query that was made so you can use it when sorting. In my answer about underlining the search term in results, I cache the query through the loading
templating method, which is always triggered whenever a search is being made. That same method can be used here as well.
var query = {};
$element.select2({
language: {
searching: function (params) {
// Intercept the query as it is happening
query = params;
// Change this to be appropriate for your application
return 'Searching…';
}
}
});
So now you can build a custom sorter
method which uses the saved query
(and using query.term
as the search term). For my example sorting method, I'm using the position within the text where the search result is to sort results. This is probably similar to what you are looking for, but this is a pretty brute force method of going about it.
function sortBySearchTerm (results) {
// Don't alter the results being passed in, make a copy
var sorted = results.slice(0);
// Array.sort is an in-place sort
sorted.sort(function (first, second) {
query.term = query.term || "";
var firstPosition = first.text.toUpperCase().indexOf(
query.term.toUpperCase()
);
var secondPosition = second.text.toUpperCase().indexOf(
query.term.toUpperCase()
);
return firstPosition - secondPosition;
});
return sorted;
};
And this will sort things the way that you are looking to do it. You can find a full example with all of the parts connected together below. It's using the three example options that you mentioned in your question.
var query = {};
var $element = $('select');
function sortBySearchTerm (results) {
// Don't alter the results being passed in, make a copy
var sorted = results.slice(0);
// Array.sort is an in-place sort
sorted.sort(function (first, second) {
query.term = query.term || "";
var firstPosition = first.text.toUpperCase().indexOf(
query.term.toUpperCase()
);
var secondPosition = second.text.toUpperCase().indexOf(
query.term.toUpperCase()
);
return firstPosition - secondPosition;
});
return sorted;
};
$element.select2({
sorter: sortBySearchTerm,
language: {
searching: function (params) {
// Intercept the query as it is happening
query = params;
// Change this to be appropriate for your application
return 'Searching…';
}
}
});
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>
<select style="width: 50%">
<option>banana orange apple</option>
<option>banana apple orange</option>
<option>apple banana orange</option>
</select>