[php] JavaScript equivalent of PHP's in_array()

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?

This question is related to php javascript phpjs

The answer is


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

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
}

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. :)


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

$.inArray( 10, [ 8, 9, 10, 11 ] );

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


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;
}

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;

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.


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


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");

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;
}

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.


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 :-)


function in_array(needle, haystack){

    return haystack.indexOf(needle) !== -1;
}

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)


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

it looks like

_x000D_
_x000D_
let myArray = ['Kevin', 'Bob', 'Stuart'];_x000D_
if( myArray.includes('Kevin'))_x000D_
console.log('Kevin is here');
_x000D_
_x000D_
_x000D_


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;
}

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.