Nyx

Chapter 15 · Beyond the DOM

Searching lists

People make typos when they search: "kolkta", "rahul kumr", "mumbay". In this chapter you'll build search boxes that still find the right thing, for lists of words, lists of records, and lists already on the page, and suggest "Did you mean...?" when nothing matches.

How Nyx search works

A plain search only finds exact text, so one wrong letter finds nothing. Nyx's search is more forgiving, and follows a few simple rules:

RuleExample
Capitals and accents don't matter"KOLKATA" and "bengaluru" find "Kolkata" and "Bengalūru".
Part of a word is enough"kol" finds "Kolkata" and "Kolar".
Small typos are forgiven"kolkta" finds "Kolkata". Longer words may have more mistakes: about one for every four letters.
Short words must be exactWords of one or two letters, like "de", aren't corrected, or they'd match almost everything.
Every word must match"rahul kol" finds Rahul from Kolkata, not every Rahul.
Best matches come firstExact matches beat typo matches, and if anything matches exactly, typo matches are left out.

Searching a list of words

Give nyx.search() a list and the text to look for. It gives back a new list of the matches, best first:

nyx.search(search cities,this list "kolkta"for this )Done

Type a city, with or without mistakes:

    Empty the box and the whole list comes back: searching for nothing matches everything. Try "pne", "hydrabad" and "del".

    Searching records

    Real data is usually a list of records, like students with a name, a city and marks. Add a list of the fields to search as the third value:

    nyx.search(students, "rahul kumr", ["name", "city"]);

      Try "rahul" (both Rahuls), "rahul delhi" (just one), and "dehli" (a typo in a city).

      FieldsWhat's searched
      ["name"]Only the name.
      ["name", "city"]The name and the city together.
      ["address.city"]A field inside another field, with a dot: { address: { city: "Pune" } }.
      No list at allEvery field of each record.

      Spell a field wrong, like ["nmae"], and Nyx tells you which fields the records really have.

      Filtering a list on the page

      Sometimes the list is already on the page, written in HTML. Use .search() on the elements: it gives back the ones whose text matches, in their page order. Hide everything, then show the matches:

      • When does the library open?
      • How do I join the science club?
      • Where is the lost and found?
      • When are the half-yearly exams?
      • How do I get a new ID card?

      nyx.search(list, text)

      nyx.search(cities, "kol")

      Searches data in JavaScript. Gives back data, best match first.

      elements.search(text)

      nyx("#faq li").search("kol")

      Searches elements on the page by their text. Gives back elements, in page order.

      Counts and "no results"

      A search that finds nothing should say so, rather than showing an empty space. .length tells you how many matches there are, and nyx.plural() from Formatting words the count:

        1. found.length === 0Nothing matched, so show a message and stop. return leaves the function early.
        2. found.slice(0, 5)Show at most the five best matches. .slice(0, 5) takes the first five items of a list.

        Empty the box to see all eight books counted, but only five shown.

        "Did you mean...?": nyx.closest

        nyx.closest() picks the one choice closest to what was typed, or gives null if nothing is close. It's how Nyx itself suggests fixes for your typos. Here it offers a button that fixes the word:

        ToolGives back
        nyx.search(list, text)Every match, best first. For search boxes.
        nyx.closest(text, list)The single closest choice, or null. For "Did you mean...?".

        Very big lists

        Searching in the browser is fast for lists of a few thousand items, which covers most school and shop websites. For bigger data, like every book in a city library, let the server search, and ask it as the person types. You did exactly that in Servers and AJAX, with nyx.debounce() and { latest: "search" }.

        Putting it together

        A "Find a classmate" box: it searches names and cities, counts the matches, and suggests a name when nothing matches:

          1. classmates.map((c) => c.name)A list of just the names, for nyx.closest(). .map() makes a new list by changing each item.
          2. nyx.search(classmates, q, ["name", "city"])Search both fields, so "kolkata" finds everyone from Kolkata.
          3. nyx.closest(q, names)When the search finds no one, look for the closest whole name, and mention it if there is one.

          Try "kolkata", "kabeer" and "ishita salt". Then "snea ry": too many typos for the search, but close enough for a suggestion. And "xyz", which is close to nothing at all.

          Common mistakes

          MistakeFix
          Searching records without fieldsThat searches every field, even ones you don't show. List the fields: ["name", "city"].
          One field without a listWrite ["name"], not "name".
          A field name with a typoIt must match the records exactly. Nyx tells you the real field names.
          Using nyx.search() on page elementsUse nyx("#list li").search(text) for elements, and nyx.search() for data.
          An empty space when nothing matchesCheck found.length === 0 and show a message.
          Expecting two-letter typos to be fixedVery short words must be exact, or they'd match almost everything.

          Exercise

          Fill in the blanks, then press Check answers.

          1. Search the list fruits for "banan".

          const found = nyx.(fruits, "banan");

          2. Search the students' names and cities.

          nyx.search(students, q, ["name", ""]);

          3. Search a field inside address.

          nyx.search(people, q, ["address."]); // { address: { city: "Pune" } }

          4. Show only the list items on the page that match.

          items.hide();
          items.(box.value()).show();

          5. Did the search find nothing?

          if (found. === 0) { ... }

          6. Keep only the first five matches.

          found.(0, 5);

          7. Find the one city closest to "mumbay".

          const guess = nyx.("mumbay", cities);

          Remember

          Nyx search ignores capitals and accents, matches parts of words, and forgives small typos.
          nyx.search(list, text) gives back the matching data, best first. Empty text gives back everything.
          For records, list the fields to search: ["name", "city"].
          nyx("#list li").search(text) finds matching elements on the page, in page order.
          Show a message when found.length === 0, and use .slice(0, 5) to show only the best few.
          nyx.closest(text, list) gives the closest choice for "Did you mean...?", or null.