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

80
Visualizações
comparing two arrays to create a new array

This seems like a very straightforward problem but for the life of me, I can not get it sorted.

I want to compare two arrays and if the value of array2 is in array1 push it to a new array otherwise push a 0.

these are my arrays:

let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let arrayTwo = [3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16];

desired outcome is

[0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]

current attempt with obvious indices issues

let newArray = [];

for (let i=0; i < arrayOne.length; i++){
  if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);
  else newArray.push(0);
};

current result

[0, 0, 0, 8, 9, 10, 0, 0, 13, 14, 15, 16, undefined, undefined, undefined, undefined, undefined, 0]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Issue with your approach is that you are searching for an index in arrayTwo

if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);

where i is the index not a value. That's why you are getting undefined values, because arrayTwo has less values then arrayOne, so index of arrayOne will not exists in arrayTwo.

Instead you should search for value in arrayTwo

for (let i=0; i < arrayOne.length; i++){
  let value = arrayOne[i];
  if(arrayTwo.includes(value)) newArray.push(value);
  else newArray.push(0);
};

If you check only for existence of the value in collection - use Set which designed exactly for this purpose.

let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let values = new Set([3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16]);

const result = arrayOne.map(value => values.has(value) ? value : 0);
// => [0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]
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