Home > Back-end >  Search alphabets in array of string efficiently using javascript
Search alphabets in array of string efficiently using javascript

Time:06-14

I have an array of products as below

const totalProducts = ['washing machine', 'sewing machine', 'refrigerator', 'desk']

If a user types any word on the input field, i want to get all matching products from the array. for e.g. if user types 'ma', then i would expect the result to contain ['washing machine', 'sewing machine']

In order to achieve the desired result, i do this code below

var result = totalProducts.filter((product) => product.includes('ma'));

I know this above code works to get the desired result. but suppose the totalProducts array has a length of over 1000. Will my method above efficiently give the result as it should ?

Or is there a better way to search and improve performance of my code ?

CodePudding user response:

Since suffix tree

(Thanks to this site for the visualisation.) If you want to find the strings that contain "po", starting from the root, take the "p" node, then the "o" node (here collapsed into the "ot$" node). The subtree under it contains links to strings #3 and #4 (this site indexes them from 1), i.e. "pot" and "spot". (This site also notes that the substring starts at position 1 for "pot" and position 2 for "spot", but for your purpose this information is not required.)

As you can see, the process of finding the matching strings is very fast; but the requisite suffix tree would be much larger than the original list. If you want to restrict the search to only match the start of words (for example, "ma" would match "washing machine", but "chi" would not), you could reduce the tree size.

However, the gains would, for most purposes, be negligible for a single search; this would probably only be needed if you need to perform the search repeatedly, fast. For an array of thousands of elements and a single lookup once in a while, your original approach is almost certainly good enough. The suffix tree approach is faster, but for the use case in the OP, an overkill, and a case of premature optimisation.

  • Related