Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - check array for value [duplicate]

I have a simple array with bank holidays:

var bank_holidays = ['06/04/2012','09/04/2012','07/05/2012','04/06/2012','05/06/2012','27/08/2012','25/12/2012','26/12/2012','01/01/2013','29/03/2013','01/04/2013','06/05/2013','27/05/2013']; 

I want to do a simple check to see if certain dates exist as part of that array, I have tried:

if('06/04/2012' in bank_holidays) { alert('LOL'); } if(bank_holidays['06/04/2012'] !== undefined) { alert 'LOL'; } 

And a few other solutions with no joy, I have also tried replacing all of the forwarded slashes with a simple 'x' in case that was causing issues.

Any recommendations would be much appreciated, thank you!

(edit) Here's a jsFiddle - http://jsfiddle.net/ENFWe/

like image 581
Nick Avatar asked Jun 13 '12 13:06

Nick


People also ask

How do you find duplicate values 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. }

How do you check if an array contains the same value?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.


1 Answers

If you don't care about legacy browsers:

if ( bank_holidays.indexOf( '06/04/2012' ) > -1 ) 

if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:

if ( $.inArray( '06/04/2012', bank_holidays ) > -1 ) 
like image 78
Florian Margaine Avatar answered Sep 21 '22 14:09

Florian Margaine