Reputation: 8079
Suppose we have an array of strings, like this:
var arr = ['qwe', 'rty', 'uio p', 'a', 's df'];
but much longer. And a string, which is the user input.
So, on every keyup
(next character inserted in that string) I have to check if this string is present in that array.
I know I can do it by looping through the array every time - but is there any way to make it faster?
Upvotes: 1
Views: 1061
Reputation: 13396
Use IndexOf()
:
var arr = ['qwe', 'rty', 'uio p', 'a', 's df'];
arr.indexOf('a'); // returns 3
arr.indexOf('aaa'); // returns -1
Upvotes: 2
Reputation: 9929
You can use the indexOf() function for that.
var arr = ['qwe', 'rty', 'uio p', 'a', 's df'];
var str= 'rty';
var isPresent = (arr.indexOf(str) > -1);
To explain: indexOf() return the index of the string found in the array. If the string is not found, it returns -1. So...indexOf('qwe') returns 0, indexOf('rty') returns 1, etc. But indexOf('foo') returns -1.
Upvotes: 8