236

Is there a way in JavaScript to compare values from one array and see if it is in another array?

Similar to PHP's in_array function?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
roflwaffle
  • 25,570
  • 20
  • 66
  • 94
  • 1
    FIRST SEE THIS ANSWER: https://stackoverflow.com/questions/784012/javascript-equivalent-of-phps-in-array#answer-40717204 tldr; `var a = [1, 2, 3]; a.includes(2); // true` – WEBjuju Jul 03 '20 at 18:41

20 Answers20

263

No, it doesn't have one. For this reason most popular libraries come with one in their utility packages. Check out jQuery's inArray and Prototype's Array.indexOf for examples.

jQuery's implementation of it is as simple as you might expect:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

If you are dealing with a sane amount of array elements the above will do the trick nicely.

EDIT: Whoops. I didn't even notice you wanted to see if an array was inside another. According to the PHP documentation this is the expected behavior of PHP's in_array:

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}

if (in_array('o', $a)) {
    echo "'o' was found\n";
}

// Output:
//  'ph' was found
//  'o' was found

The code posted by Chris and Alex does not follow this behavior. Alex's is the official version of Prototype's indexOf, and Chris's is more like PHP's array_intersect. This does what you want:

function arrayCompare(a1, a2) {
    if (a1.length != a2.length) return false;
    var length = a2.length;
    for (var i = 0; i < length; i++) {
        if (a1[i] !== a2[i]) return false;
    }
    return true;
}

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(typeof haystack[i] == 'object') {
            if(arrayCompare(haystack[i], needle)) return true;
        } else {
            if(haystack[i] == needle) return true;
        }
    }
    return false;
}

And this my test of the above on it:

var a = [['p','h'],['p','r'],'o'];
if(inArray(['p','h'], a)) {
    alert('ph was found');
}
if(inArray(['f','i'], a)) {
    alert('fi was found');
}
if(inArray('o', a)) {
    alert('o was found');
}  
// Results:
//   alerts 'ph' was found
//   alerts 'o' was found

Note that I intentionally did not extend the Array prototype as it is generally a bad idea to do so.

DOOManiac
  • 5,556
  • 6
  • 39
  • 63
Paolo Bergantino
  • 449,396
  • 76
  • 509
  • 431
99

There is now Array.prototype.includes:

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

var a = [1, 2, 3];
a.includes(2); // true 
a.includes(4); // false

Syntax

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)
brasofilo
  • 23,940
  • 15
  • 86
  • 168
alemjerus
  • 7,131
  • 2
  • 30
  • 40
  • Reminder: This doesn't work in IE11 (or any other version of Internet Explorer). For the rare cases were that still needs to be supported. – Robin93K Jan 19 '21 at 13:21
67

Array.indexOf was introduced in JavaScript 1.6, but it is not supported in older browsers. Thankfully the chaps over at Mozilla have done all the hard work for you, and provided you with this for compatibility:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

There are even some handy usage snippets for your scripting pleasure.

Alex Barrett
  • 14,998
  • 3
  • 48
  • 51
  • This is a nicer/safer/better implementation of the links/code posted here already; the specs don't call for checking for arrays inside the haystack, and that's what the OP wants. – Paolo Bergantino Apr 24 '09 at 00:16
  • 3
    Incidentally, what's the purpose of `this.length >>> 0`? Is that a conversion to a Number type? – harto Apr 24 '09 at 05:37
  • 3
    `Array.indexOf` is now standardised by ECMAScript Fifth Edition so should be considered the proper ‘native’ way of doing it. You will still need to sniff and provide this backup for older browser for a long time, though. @harto: yes, it converts `this.length` to a Number that can be represented as a 32-bit unsigned integer. A native `Array` can only have a length that already complies with this, but the spec states that you can call `Array.prototype` methods on native-JS objects that are not `Array`. This and the other pedantic argument checking stuff is to guarantee absolute spec-compliance. – bobince Sep 15 '10 at 10:24
  • 3
    There's a different polyfill version available directly from Mozilla - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – Algy Taylor Jul 23 '14 at 09:17
  • @harto I answer 8 years after your comment but maybe someone else could have the same question => see https://stackoverflow.com/questions/1822350/what-is-the-javascript-operator-and-how-do-you-use-it – Frosty Z May 30 '17 at 08:23
16

PHP way:

if (in_array('a', ['a', 'b', 'c'])) {
   // do something if true
}

My solution in JS:

if (['a', 'b', 'c'].includes('a')) {
   // do something if true
}
fsevenm
  • 429
  • 6
  • 15
14

If the indexes are not in sequence, or if the indexes are not consecutive, the code in the other solutions listed here will break. A solution that would work somewhat better might be:

function in_array(needle, haystack) {
    for(var i in haystack) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

And, as a bonus, here's the equivalent to PHP's array_search (for finding the key of the element in the array:

function array_search(needle, haystack) {
    for(var i in haystack) {
        if(haystack[i] == needle) return i;
    }
    return false;
}
random_user_name
  • 23,924
  • 7
  • 69
  • 103
11

You can simply use the "includes" function as explained in this lesson on w3schools

it looks like

let myArray = ['Kevin', 'Bob', 'Stuart'];
if( myArray.includes('Kevin'))
console.log('Kevin is here');
Dharman
  • 21,838
  • 18
  • 57
  • 107
9

There is a project called Locutus, it implements PHP functions in Javascript and in_array() is included, you can use it exactly as you use in PHP.

Examples of use:

in_array('van', myArray);

in_array(1, otherArray, true); // Forcing strict type
Marcio Mazzucato
  • 7,849
  • 6
  • 60
  • 75
  • 5
    There is also a inArray function in JQuery's APIs. Check http://api.jquery.com/jQuery.inArray/ – ahPo Oct 21 '13 at 20:19
  • @ahPo, Nice! But the Locutus implementation has the advantage to be pure javascript with no dependencies. So, choose the best one for your needs – Marcio Mazzucato Jul 08 '17 at 22:39
  • 1
    or you can just import the required [function](http://locutus.io/php/array/in_array/) from Locutus. – Niket Pathak Sep 14 '17 at 15:59
6

jQuery solution is available, check the ducumentation here: http://api.jquery.com/jquery.inarray/

$.inArray( 10, [ 8, 9, 10, 11 ] );
Webars
  • 4,668
  • 6
  • 34
  • 50
  • 3
    don't forget to check like this: if($.inArray( 10, [ 8, 9, 10, 11 ] ) > -1) because I did like this: if($.inArray( 10, [ 8, 9, 10, 11 ] )) and it always returns true – temirbek May 07 '18 at 14:11
  • PS: This is type sensitive so if checking for numbers make sure your datatypes match! ie: $.inArray( '10', [ 8, 9, 10, 11 ] ); would return -1 – Oliver M Grech Sep 30 '19 at 10:59
5
var a = [1,2,3,4,5,6,7,8,9];

var isSixInArray = a.filter(function(item){return item==6}).length ? true : false;

var isSixInArray = a.indexOf(6)>=0;
Rax Wunter
  • 2,400
  • 3
  • 22
  • 28
4

There is an equivalent function:

includes()

Look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Berry M.
  • 449
  • 5
  • 16
Jacek Dziurdzikowski
  • 1,393
  • 11
  • 20
3

If you need all the PHP available parameters, use this:

function in_array(needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    }
    else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
    return false;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Andres SK
  • 10,054
  • 20
  • 85
  • 138
3

Add this code to you project and use the object-style inArray methods

if (!Array.prototype.inArray) {
    Array.prototype.inArray = function(element) {
        return this.indexOf(element) > -1;
    };
} 
//How it work
var array = ["one", "two", "three"];
//Return true
array.inArray("one");
3

If you only want to check if a single value is in an array, then Paolo's code will do the job. If you want to check which values are common to both arrays, then you'll want something like this (using Paolo's inArray function):

function arrayIntersect(a, b) {
    var intersection = [];

    for(var i = 0; i < a.length; i++) {
        if(inArray(b, a[i]))
            intersection.push(a[i]);
    }

    return intersection;
}

This wil return an array of values that are in both a and b. (Mathematically, this is an intersection of the two arrays.)

EDIT: See Paolo's Edited Code for the solution to your problem. :)

Community
  • 1
  • 1
2
function in_array(needle, haystack){

    return haystack.indexOf(needle) !== -1;
}
TarranJones
  • 3,420
  • 1
  • 31
  • 46
crisswalt
  • 45
  • 1
  • This only returns whether it's the first element in the array; if `indexOf(needle) > 0` it will return false – DiMono Feb 05 '14 at 16:04
2
haystack.find(value => value == needle)

where haystack is an array and needle is an element in array. If element not found will be returned undefined else the same element.

2

With Dojo Toolkit, you would use dojo.indexOf(). See dojo.indexOf for the documentation, and Arrays Made Easy by Bryan Forbes for some examples.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
voidstate
  • 7,658
  • 4
  • 36
  • 50
1

I found a great jQuery solution here on SO.

var success = $.grep(array_a, function(v,i) {
    return $.inArray(v, array_b) !== -1;
}).length === array_a.length;

I wish someone would post an example of how to do this in underscore.

Community
  • 1
  • 1
pymarco
  • 6,267
  • 4
  • 25
  • 38
1
function in_array(what, where) {
    var a=false;
    for (var i=0; i<where.length; i++) {
        if(what == where[i]) {
            a=true;
            break;
        }
    }
    return a;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Priya
  • 1,416
  • 1
  • 14
  • 29
0

An equivalent of in_array with underscore is _.indexOf

Examples:

_.indexOf([3, 5, 8], 8); // returns 2, the index of 8 _.indexOf([3, 5, 8], 10); // returns -1, not found

Bogdan D
  • 4,473
  • 1
  • 27
  • 32
0

If you are going to use it in a class, and if you prefer it to be functional (and work in all browsers):

inArray: function(needle, haystack)
{
    var result = false;

    for (var i in haystack) {
        if (haystack[i] === needle) {
            result = true;
            break;
        }
    }

    return result;
}

Hope it helps someone :-)

MageParts
  • 139
  • 1