简体   繁体   中英

Materialize CSS Autocomplete sorting based on a specific word

I'm using Materialize CSS Autocomplete for my Google Apps Script with the data populated form my Google Contacts. I would like to be able to sort the order in which the contacts appear based on a specific word in their names. For example, lets say I have the following contacts:

  • Jason Garcia
  • Jonathan Jackson Mobile
  • Monica Stokes
  • Amy Wang Mobile
  • Aaron Bridges

I would like the contacts which contain the word Mobile to appear on top of the list and the rest in the alphabetical order:

  • Amy Wang Mobile
  • Jonathan Jackson Mobile
  • Aaron Bridges
  • Jason Garcia
  • Monica Stokes

To do that, I've been trying to use the sortFunction from the Materialize CSS documentation but with no success. How could I achieve something like that?

You can sort the array by checking if it contains the term "mobile", see below. This returns first all which do contain "mobile" and then all others.

const arr = ["Tom Mobile", "Sam", "Jess Mobile"]
arr.sort( (el1) => {
   if(el1.search(/mobile/gi) == -1) return 1
   return -1
}))

But that is for array and you do not need arrays, therefore that answer was general and not specific. Therefore I did a quick demo of what you actually wanted:

  document.addEventListener('DOMContentLoaded', function() {
    const options = {
        data : {
        "Tom mobile" : null,
        "Thomas" : null,
        "Tim mobile" : null
      },
      sortFunction : sortBy
    }
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, options);
  });
  
  // Sort function for sorting autocomplete results
  // prioritize if text contains mobile
  function sortBy(a, b) {    
    return  b.indexOf("mobile") - a.indexOf("mobile");
  }

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM