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

243
Vistas
¿Cómo insertar un elemento eliminado en la posición original en la matriz?

En el siguiente código:

  1. Primero creo una matriz de 10 elementos.
  2. A continuación, elimino 3 elementos aleatorios de esa matriz.
  3. Intento agregar esos 3 elementos aleatorios en la matriz original en las posiciones originales.

Por algún motivo, en el paso 3 anterior (en el registro de la consola FINAL ARR ), los elementos se agregan en la posición incorrecta. ¿Mi función de corte es incorrecta en el paso 3? Si es así, ¿cómo lo modifico para que sea correcto?

 // Step 1. Create array of 10 elements const originalValues = maxAmount => { let finalArray = []; for (let i = 0; i < maxAmount; i++) { finalArray.push({ key1: `key1-${i+1}`, position: i }); } return finalArray; } let finalArr = originalValues(10); const finalArrOriginalLength = finalArr.length; //Step 2. Remove 3 random elements in this case key1-2, key1-7, key1-8 const removedElements = []; finalArr = finalArr.filter(elem => { if (elem.key1 === 'key1-7' || elem.key1 === 'key1-2' || elem.key1 === 'key1-8') { removedElements.push(elem); return false; } else { return true; } }); /* Step 3. Add those 3 elements back to the original positions */ removedElements.forEach(elem => { finalArr.splice(elem.position - (finalArrOriginalLength - finalArr.length) + 1, 0, elem); }); /* The inserted elements from step 3 are being inserted in the wrong position as seen when this console.log prints out finalArr */ console.log('FINAL ARR', finalArr);

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

No hay necesidad de restar de elem.position .

Si ordena los elementos eliminados por las posiciones originales, debería poder insertarlos en esas posiciones.

Esto supone que no ha habido ningún otro cambio en la matriz.

 // Step 1. Create array of 10 elements const originalValues = maxAmount => { let finalArray = []; for (let i = 0; i < maxAmount; i++) { finalArray.push({ key1: `key1-${i+1}`, position: i }); } return finalArray; } let finalArr = originalValues(10); const finalArrOriginalLength = finalArr.length; //Step 2. Remove 3 random elements in this case key1-2, key1-7, key1-8 const removedElements = []; finalArr = finalArr.filter(elem => { if (elem.key1 === 'key1-7' || elem.key1 === 'key1-2' || elem.key1 === 'key1-8') { removedElements.push(elem); return false; } else { return true; } }); /* Step 3. Add those 3 elements back to the original positions */ removedElements.sort((a, b) => a.position - b.position).forEach(elem => { finalArr.splice(elem.position, 0, elem); }); console.log('FINAL ARR', finalArr);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Prueba esto...

 // Step 1. Create array of 10 elements const originalValues = maxAmount => { let finalArray = []; for (let i = 0; i < maxAmount; i++) { finalArray.push({ key1: `key1-${i+1}`, position: i }); } return finalArray; } let finalArr = originalValues(10); const finalArrOriginalLength = finalArr.length; //Step 2. Remove 3 random elements in this case key1-2, key1-7, key1-8 const removedElements = []; finalArr = finalArr.filter(elem => { if (elem.key1 === 'key1-7' || elem.key1 === 'key1-2' || elem.key1 === 'key1-8') { removedElements.push(elem); return false; } else { return true; } }); // Step 3. Add those 3 elements back to the original positions removedElements .sort((a,b)=>{return a.position > b.position ? 0 : 1 }); removedElements.forEach(elem => { finalArr.splice(elem.position, 0, elem); }); /* The inserted elements from step 3 are being inserted in the wrong position as seen when this console.log prints out finalArr */ console.log('FINAL ARR', finalArr);

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