40

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/

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Nick
  • 3,745
  • 20
  • 56
  • 75

3 Answers3

76

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 )
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
7

Try this:

// this will fix old browsers
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(value) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] === value) {
        return i;
      }
    }

    return -1;
  }
}

// example
if ([1, 2, 3].indexOf(2) != -1) {
  // yay!
}
ioseb
  • 16,625
  • 3
  • 33
  • 29
2

This should do it:

for (var i = 0; i < bank_holidays.length; i++) {
    if (bank_holidays[i] === '06/04/2012') {
        alert('LOL');
    }
}

jsFiddle

Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
  • Checking the complete array is not efficient in terms of computational complexity – dimib May 05 '19 at 19:32
  • Absolute rubbish and a ridiculous micro optimisation suggestion - as the OP states it's a simple array and if there is a match the OP can always break thus not checking the complete array. – Barry Kaye May 06 '19 at 20:08