Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for value in Javascript Array [duplicate]

Tags:

javascript

In SQL Server, I could say:

WHERE X IN(1,2) 

How would you rewrite the following in JavaScript:

if (X==1 || X==2) {} 
like image 489
Phillip Senn Avatar asked Mar 09 '11 21:03

Phillip Senn


People also ask

How do you check if a value is repeated in an array JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

How do you check if a number is repeated in an array?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }


2 Answers

Use indexOf to see if x is in an array.

if([1,2].indexOf(x) !== -1) 
like image 189
Peter Olson Avatar answered Oct 05 '22 23:10

Peter Olson


Using Array .includes method.

if ([1, 2].includes(x)) {   // array has x } 
like image 39
vitkon Avatar answered Oct 05 '22 23:10

vitkon