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?
You can try with Array. prototype. every() : The every() method tests whether all elements in the array pass the test implemented by the provided function.
Example 2: Check Array Using indexOf() In the above program, the indexOf() method is used with the if...else statement to check if an array contains a specified value. The indexOf() method searches an array and returns the position of the first occurrence. If the value cannot be found, it returns -1.
JavaScript Array includes()The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.
Vanilla JS
ES2016:
const found = arr1.some(r=> arr2.includes(r)) ES6:
const found = arr1.some(r=> arr2.indexOf(r) >= 0) 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 and includes(..) both return true if the given argument is present in the array.
/** * @description determine if an array contains one or more items from another array. * @param {array} haystack the array to search. * @param {array} arr the array providing items to check for in the haystack. * @return {boolean} true|false if haystack contains at least one item from arr. */ var findOne = function (haystack, arr) { return arr.some(function (v) { return haystack.indexOf(v) >= 0; }); }; As noted by @loganfsmyth you can shorten it in ES2016 to
/** * @description determine if an array contains one or more items from another array. * @param {array} haystack the array to search. * @param {array} arr the array providing items to check for in the haystack. * @return {boolean} true|false if haystack contains at least one item from arr. */ const findOne = (haystack, arr) => { return arr.some(v => haystack.includes(v)); }; or simply as arr.some(v => haystack.includes(v));
If you want to determine if the array has all the items from the other array, replace some() to every() or as arr.every(v => haystack.includes(v));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With