Robert Robert - 3 months ago 11
Javascript Question

How do I stop my conditional from running both the if clause and else clause while inside of a for loop?

I have an array I'm looping through to test if a user provided string exists within the loop. When I run the loop and do the check, it returns true on the array items it matches and false on the ones it doesn't. I know this is because I'm doing the check on each individual array item. My question is, how do I only get true if the string matches the array item?

var string = "a";
var array = ["a", "b", "c"];
for(var i = 0; i < array.length; i++){
if(string == array[i]){
console.log("Exists");
}
else{
console.log("Doesn't exist");
}
}


Right now, if I were to run this, I would see:

"Exists"
"Doesn't exist"
"Doesn't exist"

Answer

You can do it using Es6's includes(),

var str = "a";
var arr = ["a", "b", "c"];
var res = arr.includes(str);
if(res) console.log("exists");

And if you are concerning about browser support then just use indexOf(),

var str = "a";
var arr = ["a", "b", "c"];
var res = (arr.indexOf(str) > -1);
if(res) console.log("exists");