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?
There is now
Array.prototype.includes
:Add this code to you project and use the object-style inArray methods
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:
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:
And, as a bonus, here's the equivalent to PHP's array_search (for finding the key of the element in the array:
With Dojo Toolkit, you would use
dojo.indexOf()
. See dojo.indexOf for the documentation, and Arrays Made Easy by Bryan Forbes for some examples.I found a great jQuery solution here on SO.
I wish someone would post an example of how to do this in underscore.