5

I am checking a string input whether it contains any of an array of strings or not. It is passing most of the tests but not the below one.

Can anyone break my code down why it is not working properly?

     function checkInput(input, words) {
      var arr = input.toLowerCase().split(" ");
      var i, j;
      var matches = 0;
      for(i = 0; i < arr.length; i++) {
        for(j = 0; j < words.length; j++) {
          if(arr[i] == words[j]) {
            matches++;
          }
        }
      }
      if(matches > 0) {
        return true;
      } else {
        return false;
      }
    };

checkInput("Visiting new places is fun.", ["aces"]); // returns false // code is passing from this test
checkInput('"Definitely," he said in a matter-of-fact tone.', 
    ["matter", "definitely"])); // returns false; should be returning true;

Thank you for your time!

Tiyor
  • 119
  • 1
  • 1
  • 8

2 Answers2

12

You can use functional methods for this. Try Array.some.

const words = ['matters', 'definitely'];
const input = '"Definitely," he said in a matter-of-fact tone.';
console.log(words.some(word => input.includes(word)));
  • 1
    This is case sensitive. OP wants a case insensitive solution. – frogatto Oct 25 '17 at 06:54
  • Case insensitivity is irrelevant to the question. It is very, very clear that you toLowerCase the strings. Not encouraging the vamping. –  Oct 25 '17 at 06:57
  • The question is really "how to see if a string contains any of an array of strings", it's a clear duplicate on top of being a general vamp Q. It will be closed, my answer will be gone. I just want OP to see there is a better way haha –  Oct 25 '17 at 06:59
6

You can use array#includes to check if a word exist in your input and convert both your input and words in lower case and then use array#includes.

function checkInput(input, words) {
 return words.some(word => input.toLowerCase().includes(word.toLowerCase()));
}

console.log(checkInput('"Definitely," he said in a matter-of-fact tone.', 
["matter", "definitely"]));

You can create regular expression and use i flag to specify case-insensitivity

function checkInput(input, words) {
 return words.some(word => new RegExp(word, "i").test(input));
}

console.log(checkInput('"Definitely," he said in a matter-of-fact tone.', 
["matter", "definitely"]));
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51