I have an array with some values. How can I search that array using jquery for a value which is matched or close to it?
var a = ["foo","fool","cool","god"];
If I want to search for oo, then it should return foo, fool, and cool because these strings contain oo.
Vanilla JS
To search in the array with Vanilla JS I would use the
filter()method implemented into the Array prototype.Note: For very large arrays you might want to consider refactoring those to async/await functions else it might slow down the user interface.
1. Using regular expressions (slower)
This is the most flexible approach as you could search for different patterns. You should be aware that the search term here is not a plain text, thus you have to escape most of non-alphanumeric chars according to the syntax. You should not pass unprocessed user input directly to the function, as it will not work as expected.
2. Using
indexOf(faster)In this particular case I would rather use
indexOf()which is basically an equivalent ofLIKE %term%but much faster than using regular expressions when working with large arrays.It is a common case to do case-insensitive searches so make sure to use
toLowerCase()for both the search terms and the array items. Otherwise remove it everywhere from the examples.ES6 style (ES2015)
ES5 style