1

I would like to create a vuetify autocomplete with a custom filter that first shows the hits that start with the searchtext and then show the hits that not start with the searchtext, but have the searchtext somewhere in the middle.

I now have a custom filter like this, but this filter is not prioritizing words that start with the searchtext:

customFilter(item, queryText) {
    const textOne = item.description.toLowerCase();
    const textTwo = item.code.toLowerCase();
    const searchText = queryText.toLowerCase();

    return (
        textOne.indexOf(searchText) > -1 || textTwo.indexOf(searchText) > -1
        );
    }
},
fantastischIdee
  • 465
  • 2
  • 6
  • 17

1 Answers1

0

Codepen (Type 'ma' for example)

I believe you need to sort it manually, filter returns only true/false whether item is a match.

// https://stackoverflow.com/a/36114029/1981247
var _sortByTerm = function (data, term) {
    return data.sort(function (a, b) {
       // cast to lowercase
       return a.toLowerCase().indexOf(term) < b.toLowerCase().indexOf(term) ? -1 : 1;
    });
};

Then pass sorted array to items prop

<v-autocomplete :items="computedItems"

...

computed: {
  computedItems() {
    return _sortByTerm(this.states, this.search.toLowerCase())
  },
},

Note this is just to get you started, and you might need to change code a bit according to the data (and filters) you are using, e.g. _sortByTerm works only on array of strings, but in the link there is a solution for sorting arrays of objects also.

Traxo
  • 18,464
  • 4
  • 75
  • 87
  • This probably won't work when v-autocomplete's cache-items is set (by the way the Codepen doesn't work anymore, "Vue is not defined") – svenema Jun 05 '22 at 07:54