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

twana eng
  • 31
  • 10
  • 2
    Does this answer your question? [How to find index of all occurrences of element in array?](https://stackoverflow.com/questions/20798477/how-to-find-index-of-all-occurrences-of-element-in-array) – Alon Eitan Feb 01 '20 at 14:23
  • surely its if(array.indexOf(string) == -1) { ... do stuff ... } – gavgrif Feb 01 '20 at 16:00

4 Answers4

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);
}
Aaron
  • 1,600
  • 1
  • 8
  • 14
1

You can use JavaScript inbuilt functions:

var cars = ["Saab", "Volvo", "BMW","Audi"];
if(!cars.includes("Audi")) {
    console.log("OK");
}
Sukanta Bala
  • 871
  • 1
  • 9
  • 19
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
}
Emech
  • 611
  • 1
  • 4
  • 16
0

Something similar to what @Aaron suggested:

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