0

I have a gigantic list (800 items) and one really long string. I want to get the first item in the array that matches the part of the string and stored in a variable.

My code currently:

for (var i = 0; i<gigantic_genre_array.length; i++) {
  var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
  if(test_genre != -1) {
    tag1 = gigantic_genre_array[test_genre];
    alert(tag1);
  }
}

This doesn't work like I thought it would, any suggestions?

3 Answers 3

3

Try this:

for(var i = 0; i<gigantic_genre_array.length; i++){
          var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
          if(test_genre!=-1){
            tag1 = gigantic_genre_array[i];
            alert(tag1);
          }
        }
Sign up to request clarification or add additional context in comments.

3 Comments

what did you change in the original code.? I cannot see anything.? .... oops I had seen that. you jus replaced the index with i..!
he changed gigantic_genre_array[test_genre] to gigantic_genre_array[i]
tag1 = gigantic_genre_array[i]; instead of tag1 = gigantic_genre_array[test_genre];
0

Do the process reversely it will be efficient too.

var wordArray = thelongstr.split(' ');

for(var i=0,len = wordArray.length; i < len; i++)
{
  if(gigantic_genre_array.indexOf(wordArray[i]) > -1)
   {
     alert(wordArray[i]);
   }
}

Comments

0

You may create a RegExp based on the array and test it against the string:

var gigantic_genre_array=['foo','bar','foobar'];
var thelongstr='where is the next bar';

alert(new RegExp(gigantic_genre_array.join('|')).exec(thelongstr)||[null][0]);
//returns bar

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.