Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda