k102
k102

Reputation: 8079

Fastest way to find string in the array of strings

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

Answers (2)

Tzach
Tzach

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

Bas Slagter
Bas Slagter

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

Related Questions