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

167
Visualizações
Comparing two arrays and remove items in array1 where the index in array2 is undefined

Let's say I have these two arrays

steps = [0, 2, 4, 6, 8, 10, 12, 15, 20, 25, 30, 35, 40, 45, 50]

nums = [16.931728, 16.975609, 17.09624, undefined, undefined, undefined..., 5] 

Both arrays are guaranteed to always have the same length.

I want to remove all the undefined values from my nums array, and then remove items at the matching index in my steps array.

Is there a neat way to do this?

I can achieve this by doing nums.filter, and then keep track of the removed indexes in an array.

and then loop through the array of removed indexes backwards to remove the items in the steps array, but this feels wayyy messy. Is there a simply way to approach this?

The end result should be

steps = [0, 2, 4, 50]
nums = [16.931728, 16.975609, 17.09624, 5] 
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could use Array.reduce() to create the required output.

For each item in the steps array, we'll check if the corresponding nums array is undefined, if it is we skip adding to the output arrays.

let steps = [0, 2, 4, 6, 8, 10, 12, 15, 20, 25, 30, 35, 40, 45, 50]
let nums = [16.931728, 16.975609, 17.09624, undefined, undefined, undefined, undefined, undefined, undefined,  undefined, undefined, undefined, undefined, undefined, 5] 

let result = steps.reduce((acc, val, i) => { 
    if (nums[i] !== undefined) {
        acc.nums.push(nums[i]);
        acc.steps.push(val);
    }
    return acc;
}, { steps: [], nums: [] })

console.log('steps:', result.steps);
console.log('nums:', result.nums);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

You could take a single loop from the end and remove if necessary.

const
    steps = [0, 2, 4, 6, 8],
    nums = [16.931728, 16.975609, undefined, undefined, 17.09624] 

let i = nums.length;

while (i--) {
    if (nums[i] !== undefined) continue;
    steps.splice(i, 1);
    nums.splice(i, 1);
}

console.log(...steps);
console.log(...nums);

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