6

I have to check whether a variable is equal to a given number or another. For example I am doing this right now.

if (num == 1 || num == 3 || num == 4 || etc.) {
    // Do something
} else if (num == 2 || num == 7 || num == 11 || etc.) {
    // Do something
}

I thought there should be an easier way. for example an array of all numbers per if statement.

var array1 = [1,3,4,5,6,8,9,10 etc.]
var array2 = [2,7,11,12,13,14 etc.]

And then see if the number is equal to anything inside one of these arrays. But I don't know how to do it..

Andy G
  • 19,232
  • 5
  • 47
  • 69
Anders
  • 160
  • 1
  • 1
  • 9
  • 1
    JQuery - [.inArray](http://api.jquery.com/jQuery.inArray/). – Vucko Jul 29 '13 at 18:18
  • You can use [`.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf), but note that it is [not supported in IE8 or lower](http://msdn.microsoft.com/en-us/library/ie/ff679977(v=vs.94).aspx). For those browsers, you'll have to do it manually (or use jQuery's `.inArray` since jQuery is tagged here). – ajp15243 Jul 29 '13 at 18:20
  • Or, in compliant browsers: `[1,2,3,4,5].indexOf(2); // 1` – David Thomas Jul 29 '13 at 18:21

6 Answers6

11

The indexOf() method searches the array for the specified item, and returns its position.

 var array1 = [1,3,4,5,6,8,9,10];
 var a = array1.indexOf(46); //a = -1; if not found

If you need to support environments that don't have .indexOf(), you could implement the MDN fix.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";

        if (this === void 0 || this === null) throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) return -1;

        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) // shortcut for verifying if it's NaN
            n = 0;
            else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }

        if (n >= len) return -1;

        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);

        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) return k;
        }
        return -1;
    };
}
David
  • 1,829
  • 20
  • 31
10

Since you're asking for jQuery, there is .inArray(). This returns a -1 if it isn't found, else the index of the matching element.

jdepypere
  • 3,453
  • 6
  • 54
  • 84
2

You don't need to use jQuery. This is a built in function called indexOf:

if ( arr.indexOf(item) !== -1 ) {
    // item is in array
}
Jivings
  • 22,834
  • 6
  • 60
  • 101
1

why dont you do a simple for loop?

for(var i = 0; i < array1.length; i++)
{
  if(array[i] == num)
   {
     //     do something
     break;
   }
}
Armen
  • 1,083
  • 2
  • 10
  • 18
  • Because there is a function that does the same thing? – Jivings Jul 29 '13 at 18:21
  • Please consider using inArray function. – simongus Jul 29 '13 at 18:22
  • Nothing wrong with using a loop. -2 for a working and fast solution is just dumb. –  Jul 29 '13 at 18:23
  • But that function is working only on jQuery ... I think the question is mostly about javascript – Armen Jul 29 '13 at 18:23
  • ...also note that this answer is technically more correct than all the `indexOf()` or `inArray()` answers, as it maintains the type coercive comparison. Don't know if OP actually needs this, but it should be taken into consideration. –  Jul 29 '13 at 18:26
1

You might use inArray function (http://api.jquery.com/jQuery.inArray/)

<script>var arr = [ 4, "Pete", 8, "John" ];
var $spans = $("span");
$spans.eq(0).text(jQuery.inArray("John", arr));
$spans.eq(1).text(jQuery.inArray(4, arr));
$spans.eq(2).text(jQuery.inArray("Karl", arr));
$spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
</script>

Output:

"John" found at 3 4 found at 0 "Karl" not found, so -1 "Pete" is in the array, but not at or after index 2, so -1

simongus
  • 440
  • 2
  • 6
1

You can do it without jQuery:

if(array1.indexOf(num1) >= 0)//if -1, then not found
Mihail
  • 1,469
  • 11
  • 13
  • Do note, however, that `Array.prototype.indexOf` is not supported in IE8 or below. – ajp15243 Jul 29 '13 at 18:24
  • 1
    Yes, but IE8 is very old browser. Not anybody support this. – Mihail Jul 29 '13 at 18:27
  • Go work for or support a large corporation. Some of them still use IE7, and many of them are stuck on IE8. I regularly have to support IE8 at work for our clients. – ajp15243 Jul 29 '13 at 18:29