简体   繁体   中英

react-autocomplete multiple suggestions

  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().slice(0, inputLength) === inputValue
    );
  };

The current algorithm of react-autocomplete only finds the first word of a phase. For example I can only find "Coca Cola Zero Sugar Cola" when I write "coc" or"coca" but I cannot find it if I write "Cola", "Zero" or "Sugar". I asked in repo's issues but cannot get and answer. I tried myself without success. How can I write algorithm that will work as I explained above?

If you modify your filter to use .includes instead of === it will return multiple suggestions:

const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().includes(inputValue)
   );
 };

This also does it

  const getSuggestions = value => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;
    return inputLength === 0 ? [] : _products.filter(lang =>
      lang.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
    );
  };

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