I have a target array ["apple","banana","orange"]
, and I want to check if other arrays contain any one of the target array elements.
For example:
["apple","grape"] //returns true;
["apple","banana","pineapple"] //returns true;
["grape", "pineapple"] //returns false;
How can I do it in JavaScript?
What about using a combination of some/findIndex and indexOf?
So something like this:
To make it more readable you could add this functionality to the Array object itself.
Note: If you'd want to do something with a predicate you could replace the inner indexOf with another findIndex and a predicate
If you don't need type coercion (because of the use of
indexOf
), you could try something like the following:Where
arr
contains the target items. At the end,found
will show if the second array had at least one match against the target.Of course, you can swap out numbers for anything you want to use - strings are fine, like your example.
And in my specific example, the result should be
true
because the second array's3
exists in the target.UPDATE:
Here's how I'd organize it into a function (with some minor changes from before):
DEMO: http://jsfiddle.net/u8Bzt/
In this case, the function could be modified to have
targetArray
be passed in as an argument instead of hardcoded in the closure.UPDATE2:
While my solution above may work and be (hopefully more) readable, I believe the "better" way to handle the concept I described is to do something a little differently. The "problem" with the above solution is that the
indexOf
inside the loop causes the target array to be looped over completely for every item in the other array. This can easily be "fixed" by using a "lookup" (a map...a JavaScript object literal). This allows two simple loops, over each array. Here's an example:DEMO: http://jsfiddle.net/5Lv9v/
The downside to this solution is that only numbers and strings (and booleans) can be used (correctly), because the values are (implicitly) converted to strings and set as the keys to the lookup map. This isn't exactly good/possible/easily done for non-literal values.
With underscorejs
Update @Paul Grimshaw answer, use
includes
insteed ofindexOf
for more readableHere is an interesting case I thought I should share.
Let's say that you have an array of objects and an array of selected filters.
To apply the selected filters to this structure we can