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?
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?
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):
This wil return an array of values that are in both
a
andb
. (Mathematically, this is an intersection of the two arrays.)EDIT: See Paolo's Edited Code for the solution to your problem. :)
An equivalent of
in_array
withunderscore
is _.indexOfExamples:
_.indexOf([3, 5, 8], 8); // returns 2, the index of 8 _.indexOf([3, 5, 8], 10); // returns -1, not found
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:There are even some handy usage snippets for your scripting pleasure.
jQuery solution is available, check the ducumentation here: http://api.jquery.com/jquery.inarray/
If you are going to use it in a class, and if you prefer it to be functional (and work in all browsers):
Hope it helps someone :-)