Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
Strange behavior from simple conditional statement?

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' ) }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar

0

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!’);
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda