Search code examples
javascriptreactjsedit-distance

How to implement a filter that takes into account the user's typo?


I have the following pseudocode with the filter implementation, it works by coincidence with what the user entered in the input field.

When the user enters the word "tes", he sees item "test", if he writes "tesz", then he will not see items.
How can you implement the functionality that the user will allow if he typed( entered incorrectly) in a 1 letter word, still get the desired result, because it often happens that the user misses and writes the wrong letter.

!That is, I need a filter that, if you make a typo, will still display a suitable result, how can I achieve such an effect? In this case, they are not interested in any complex calculation algorithms, but at least a typo in 1 character

my code example

import React, { useState } from "react";
import "./styles.css";

const mock = ["item1", "test", "item2", 'some data'];

export default function App() {
  const [value, setValue] = useState("");
  const [items, setItems] = useState(mock);
  const [filteredItem, setFilteredItem] = useState(mock);

  const onChange = ({ target: { value } }) => {
    setValue(value);
    const filteredItems = items.filter((el) => {
      return el.includes(value);
    });
    setFilteredItem(filteredItems);
  };

  return (
    <div className="App">
      <input onChange={onChange} value={value} />
      <ul>
        {filteredItem.map((el) => {
          return <li>{el}</li>;
        })}
      </ul>
    </div>
  );
}

link to codesandbox filter_react


Solution

  • you can try this use string similarity to match the best one, is you want to match the top three values to compare and get the top matches(this string-similarity npm's rating looks like always return 0 maybe need you to find another one).

    https://codesandbox.io/s/nostalgic-lalande-muf0q?file=/src/App.js

    enter image description here