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

141
Visualizações
check array exist in array using every and some

I have arr = [1,2,3] and ids = [1,2,3,4,5,6]. I want to find if any of the arr item exist in the ids. If yes the invalid is true.

Which of the below code is better? or they are the same thing?

const invalid = !arr.every((id) => ~ids.indexOf(id));

const invalid = arr.some((id) => ids.includes(id));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The two statements have a very different semantics.

The callbacks are the same, ie ids.includes(id) === true is equivalent to ~ids.indexOf(id) != 0. But arr.some() and !arr.every() have a different semantics:

  • some() returns true if at least one element fits the condidition
  • !every() returns true if at least one element doesn't fit the condition

So actually your first snippet is not checking, if there is at least one element in arr that is also contained in ids, but if there is at least one element in arr that is not contained in ids

So the correct version of first snippet would be

const invalid = !arr.every((id) => !(~ids.indexOf(id)));

Ie, checkig if not every element of arr is not contained in ids. From a computational standpoint, they are more or less the same:

  • indexOf and includes return on the first element element they find
  • some stops when the callback returns true for the first time
  • every stops when the callback returns false for the first time
  • there is of course a (little) overhead for ~ and !

But if you compare this to your second snippet, it seems pretty obvious, that it is far more complex to read and understand and therefore far more complex to maintain.

const 
  arr = [1,2,3],
  ids = [1,2,3,4,5,6]
  
const 
  i1 = !arr.every((id) => ~ids.indexOf(id)),
  i2 = arr.some((id) => ids.includes(id)),
  i3 = !arr.every((id) => !(~ids.indexOf(id)));
  
  
console.log(i1, i2, i3)

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