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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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: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:And this my test of the above on it:
Note that I intentionally did not extend the Array prototype as it is generally a bad idea to do so.