0

I want to check if a string in an array has only a certain word.

var nonessential = function(){
for (var i=0; i < arr.length; i++){
    var stringnumber = arr[i];
if (stringnumber.indexOf("the")>-1 || stringnumber.indexOf("this")>-1 || stringnumber.indexOf("than")>-1 || stringnumber.indexOf("a")>-1){
}else{
    essential = arr.slice(i,1)
    console.log(essential)
}
}

So, for example, if the array was ["hey","man","a","this"], I want the new array (essential) to be ["hey","man"]. The problem is, because the indexOf checks for a, so it eliminates "man". I only want to eliminate the array value if the string is ONLY "a", not it if includes it. Any solutions?

2
  • 5
    Why are you using indexOf when you want simple string equality? Use ==. Commented Nov 30, 2015 at 1:14
  • Listen to meagar. This is not C and indexOf is not strcmp. You don't need to use functions to compare string equality in a modern language. Commented Nov 30, 2015 at 3:17

1 Answer 1

3

Have a look at filter. You can use it to remove items from an array based on a predicate function.

function nonessential(words) {
  var targetWords = ['the', 'targetRegexthis', 'than', 'a'];
  return words.filter(function(word) {
    return targetWords.indexOf(word) < 0;
  });
}

Maybe think about using Regular expressions for more fine grained control when specifying non-essential words.

Sign up to request clarification or add additional context in comments.

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.