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

136
Visualizações
Delete all elements from an array A which are present in an array B without using a double loop

So, as an input I have two arrays, A and B. Let's suppose that these are the values inside the two:

A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and B = [1, 3, 5, 7, 9]

After the deletion the array A should be [2, 4, 6, 8, 10].

I have written (Javascript) this functioning algorithm to solve this problem:

for (var i=0; i < A.length; i++) {
   for (var j=0; j < B.length; j++) {
      if(B[j] == A[i]) 
         A.splice(i, 1) // Removes 1 element of the array starting from position i 
   }
}

I would like to know, is it possible to solve this problem without using a double loop?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

What about this:

let A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ;
const B = [1, 3, 5, 7, 9];

A = A.filter(num => !B.includes(num));
about 4 years ago · Juan Pablo Isaza Relatório

0

Yes it is. You could use a Set. In terms of Set operations you are computing the difference A \ B.

Using a set which is optimized for lookups in O(1) time will speed up the computing the difference siginificantly from O(n²) when using includes() or double for loop to O(n).

const A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const B = [1, 3, 5, 7, 9]
const setB = new Set(B);
const difference = A.filter(x => !setB.has(x));
console.log(difference);

about 4 years ago · Juan Pablo Isaza Relatório

0

Maybe that ?

const
  A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
, B = [1, 2, 3, 5, 7, 9]   // no gaps in 1,2 and 2,3
  ;

for (let i =0, j=0 ; i < A.length; i++)
  {
  if (A[i]===B[j]) { A.splice(i--,1); j++ }
  }
  
document.write( JSON.stringify(A) )

or (faster code)

const
  A = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
, B = [ 1, 3, 5, 7, 9 ]
  ;

for (let i = A.length, j= B.length -1 ; i-- ; )
  {
  if (A[i]===B[j]) { A.splice(i,1); j-- }
  }
  
document.write( JSON.stringify(A) )

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