Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda