twana eng
twana eng

Reputation: 31

compare a string with all elements of array in a single loop

I have a string and an array. Let's say there are 5 elements in array now i want to perform a function that if that string is not equal to any value of array then perform function. I simply used a loop to iterate the array for example: I have array

var cars = ["Saab", "Volvo", "BMW","Audi"];
String output ="Audi";
for(let i=0;i<cars.length;i++)
{
   if(output != cars[i])
     {
      // run a code
     }
}

But the problem comes for example the element at index 0 in array is not equal to the string so the condition in loop runs. I want to check whole array in single loop. In simple words, I want to run a function if the value of string does not equal any value of string in javascript

Upvotes: 0

Views: 1555

Answers (4)

Sukanta Bala
Sukanta Bala

Reputation: 879

You can use JavaScript inbuilt functions:

var cars = ["Saab", "Volvo", "BMW","Audi"];
if(!cars.includes("Audi")) {
    console.log("OK");
}

Upvotes: 1

Pavlo
Pavlo

Reputation: 649

Something similar to what @Aaron suggested:

const car = 'Saab';
const carInArray = ["Saab", "Volvo", "BMW","Audi"].find(item => item === car);
if(carInArray) { //do work };

Upvotes: 0

Aaron
Aaron

Reputation: 1737

Why dont you use the inbuilt function includes? Just check for it in a simple if condition and run your code in it.

var cars = ["Saab", "Volvo", "BMW","Audi"];
let output ="VW";
if(!cars.includes(output)){
  console.log(output);
}

Upvotes: 4

Emech
Emech

Reputation: 631

Check out this please.

var cars = ["Saab", "Volvo", "BMW","Audi"];
var output = "Audi";
var isFound = false;
for(let i=0; i<cars.length; i++) {
   if(output === cars[i]) {
      isFound = true;
      break;
   }
}
if (!isFound) {
   // Do Code
}

Upvotes: 0

Related Questions