0

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

2

4 Answers 4

4

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);
}

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

Comments

1

You can use JavaScript inbuilt functions:

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

Comments

0

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
}

Comments

0

Something similar to what @Aaron suggested:

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

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.