I compared three possible implementations:
Alternative 1 - Using for loop:
function alternative1(aValidWords, sMainWordLower) {
var aPossibleWords1 = [];
for(i=0; i < aValidWords.length; i++){
if(sMainWordLower.indexOf(aValidWords[i]) != -1){
aPossibleWords1.push(aValidWords[i]);
}
}
return aPossibleWords1;
}
Alternative 2 - Using jQuery grep function:
function alternative2(aValidWords, sMainWordLower) {
return $.grep(aValidWords, function(word) {
return sMainWordLower.indexOf(word) != -1;
}
)
}
Alternative 3 - Using JavaScript native filter method (IE9, Chrome, Firefox, Opera, Safari):
function alternative3(aValidWords, sMainWordLower) {
return aValidWords.filter(function(word) {
return sMainWordLower.indexOf(word) != -1;
}
)
}
I measured the execution times with Chrome Profile tool. Each alternative was executed 10 times with array of random milion words. The results are:
- Alternative 1: 20 executions -> 21,68s
- Alternative 2: 20 executions -> 26,31s
- Alternative 3: 20 executions -> 34,66s
I was surprised by the fact, that native JavaScript Filter function was so slow.
If you wan't to measure execution times by yourself, there is jsFiddle - it will take some time for script to finish.
In general those three alternatives are easiest. If those execution times suits you, use one of them, otherwise the answer of @Pumbaa80 is the right one.
[UPDATE]
For the explanation of the results (why JQuery grep funcion is faster then native JavaScript filter function) please take a look at this question/answer.
jsFiddle code was also ported to jsPerf thanks to @Alexander.