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?
It can be done by simply iterating across the main array and check whether other array contains any of the target element or not.
Try this:
DEMO at JSFIDDLE
ES6 (fastest)
ES2016
Underscore
DEMO: https://jsfiddle.net/r257wuv5/
jsPerf: https://jsperf.com/array-contains-any-element-of-another-array
I found this short and sweet syntax to match all or some elements between two arrays. For example
// OR operation. find if any of array2 elements exists in array1. This will return as soon as there is a first match as some method breaks when function returns TRUE
// prints TRUE
// AND operation. find if all of array2 elements exists in array1. This will return as soon as there is a no first match as some method breaks when function returns TRUE
// prints FALSE
Hope that helps someone in future!
If you're not opposed to using a libray, http://underscorejs.org/ has an intersection method, which can simplify this:
The intersection function will return a new array with the items that it matched and if not matches it returns empty array.
My solution applies Array.prototype.some() and Array.prototype.includes() array helpers which do their job pretty efficient as well
ES6
Vanilla JS - single line
ES2016:
ES6:
How it works
some(..)
checks each element of the array against a test function and returns true if any element of the array passes the test function, otherwise, it returns false.indexOf(..) >= 0
andincludes(..)
both return true if the given argument is present in the array.