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

327
Vistas
How to chain two splice methods in Javascript?

In the following example, splice().splice() didn't work. What am I missing? How can I chain two splice methods in a single line? Thank you for any advice!

function test() {

  var data = [0,1,2,3,4,5];
  data.splice(0,2).splice(-1);  // Removed only the first two elements, but not the last element.
  console.log(data) // Returned [ 2, 3, 4, 5 ]

  var data = [0,1,2,3,4,5];
  data.splice(0,2); // Removed the first two elements.
  data.splice(-1);  // Removed the last element.
  console.log(data) // Returned [ 2, 3, 4 ]

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

0

splice returns the removed elements, so chaining them in a single statement won't really work - you don't want to operate on the removed elements, you want to operate on the original array both times.

Usually, in this sort of situation, the right approach is to use slice instead, which is both easier to work with (just specify a start (inclusive) and end (exclusive) index) and is more functional (you get a new array instead of mutating an existing one - it's nice to avoid mutation when possible, makes code more understandable).

const data = [0,1,2,3,4,5];
console.log(data.slice(2,5));

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