I’m building an Ionic app. The app contains an array of 20k “word” objects with the word and pronunciation. This data is all local and is used via a service.
There’s a search page with a search input that on keydown makes a new search request and updates the “DOM.” The time it takes to run my search function takes a few seconds depending on the search, so the user can’t even type multiple characters without delay.
I’ve tried just running the function without the DOM aspect and it’s still slow.
I’ve even tried rewriting my .filter() function as a for loop with various limits for the number of results, but if there isn’t a match, the whole 20k array of items will be searched.
Is there a faster way to make this search function, or do I just need to reduce my dataset? Is there a good tutorial for something like this?
Not sure how my code doesn’t make any sense. The only weird thing is that when I pasted the code in the for loop the less than rendered as < . It’s to keep the results from being too long;
I also found myself curious after reading this post, and feel like the most viable solution is what @AaronSterling suggested. Maybe not that particular solution, but it seems like you would need assistance from some sort of library / helper npm package.
In the end, “filtering 20,000 objects” and “fast” doesn’t seem viable without some outside help.
@JAR19 might be on to something in the sense that adding some sort of additional property to streamline the process would be helpful. Maybe separating arrays by “noun” and “verb”, etc
I add 20k random words in the dictionary then look for a string of 3 letters. The solution is found in general in less than 10 ms…
Here is the search function:
function findWord(start){
return dictionary.filter(function(e){
return e.word.startsWith(start);
})
}
I even try to make all the words starts with the same letters: solution is found in 20ms so still acceptable (without limiting the number of output which should be even faster)
UPDATE FROM OP:
I moved my function from running on keydown on my search bar to a specific search button. I’m not sure why, but this drastically increased performance to < a second.
What if the base of words is not 20 thousand, but 50 or 100?
It is not necessary to keep such amounts of data on mobile devices.
Now you have a search on startWith, but if you search with contains? How to quickly replenish this database to the end user?
I see here two options:
still store data on the server, use there for example an elastic search, from the client to receive data requests, at least on startWith, though on contains, even spelling a word with errors (via n-grams)
if you still store data offline, you can store words in different tables, for example, depending on the first letter (two, three …).
Also it is possible together with a base of words to drag the base of n-grams and to do a search on it.