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

216
Vistas
How to swap two elements of an array with empties in JavaScript?

I have an array and I want to swap two elements in the array. If the array is non-empty, I can simply do:

const swap = (arr, a, b) => {
    const temp = arr[a]
    arr[a] = arr[b]
    arr[b] = temp
}

and the function can correctly swap the value of the index a and b in the array arr.

However, if the array has some empty elements, such as [1, , , ,], and the result of the swap will be [undefined, empty, 1, empty], while the expected result should be [empty × 2, 1, empty]. So how do I modify the swap function so that the result will be correct. Or is there any way to make a specific index to be empty in an array?

Also failed:

const swap = (arr, a, b) => {
    const temp = arr[a]
    arr.splice(a, 1, arr[b])
    arr.splice(b, 1, temp)
}

Original Problem:

I have an array let arr = [1, , , ,] (which will show [1, empty × 3] in console) with length 4, and I want to move the first element to the third, that is: [empty × 2, 1, empty]. How do I achieve that?

I have tried splice and directly assign value to the array but they won't work.

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

0

You do need splice - combined with shift to get the first item

let arr = [1, , , ,]

console.log(arr)

arr.splice(2, 0, arr.shift());
console.log(arr)

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