Trying to run a simple check on an Array of Strings to see if it contains any elements from another Array of Strings but running into some unexpected behavior. In the tests below, both arrays have the b string.
However, the conditional statements do not seem to recognize it. Why is this happening?
const array1 = [ 'a', 'b', 'c', 'd' ] ;
const array2 = [ 'e' , 'f' , 'g' , 'b' ] ;
// test 1
array1.includes( ...array2 ) ?
console.log( 'error' ) :
console.log( 'no error' ) ;
// test 2
array1.includes( 'e' , 'f' , 'g' , 'b' ) ?
console.log( 'error' ) :
console.log( 'no error' ) ;
// test 3
if( array1.includes( 'e' , 'f' , 'g' , 'b' ) ) { console.log( 'error' ) }
else { console.log( 'no error' ) }
you can check if an array contains any element of another by using ES6 some
const found = arr1.some(r=> arr2.includes(r))
const array1 = [ 'a', 'b', 'c', 'd' ] ;
const array2 = [ 'e' , 'f' , 'g' , 'b' ] ;
const found = array1.some(r=> array2.includes(r));
console.log(found);
I think you may be misusing Array.prototype.includes. I think from the docs that it only is intended to check for the presence of a single element. Spreading values into it will result in unexpected behavior as JavaScript functions can take arbitrarily many arguments without causing an error but they may not be used.
To achieve the results you’re looking for, I would probably reach for aSet
// this would work
const overlap = test1.filter(t => test2.includes(t));
// this might be faster (would have to benchmark but theoretically)
const s1 = new Set(test1);
const s2 = new Set(test2);
const overlap2 = s1.filter(t => s2.has(t));
if(overlap.length > 0) {
console.log(‘overlap!’);
}
if(overlap2.size > 0) {
console.log(‘overlap!’);
}