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

350
Vistas
Why is the splice function removing items from the beginning, not the end here? (Javascript)

I'm trying to write a function in Javascript that accepts a nested array and number as two arguments and returns a new nested array with the last couple items removed in each inside array as indicated by the number argument.

For example:

*/ removeColumns([[1, 2, 3, 4],
               [1, 2, 3, 4],
               [1, 2, 3, 4],
               [1, 2, 3, 4]], 2);
   => [[1, 2],
       [1, 2],
       [1, 2],
       [1, 2]]
*/

I am attaching the code have written so far. This gives me a return of [[3, 4], [3, 4]. I thought the splice function always removes array elements after the provided index but here it seems to be removing elements before the index. What am I doing wrong here?

const removeColumns = (originalGrid, numColumns) => {
    for (let i = 0; i < originalGrid.length; i++) {
        console.log(originalGrid[i].splice(originalGrid.length - numColumns, numColumns))
        console.log(originalGrid[i])
    }
    return originalGrid
}


let originalGrid = [
    [1, 2, 3, 4],
    [1, 2, 3, 4]
  ];

console.log(removeColumns(originalGrid, 2))
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I think that should fix your issue:

        originalGrid[i].length - numColumns, numColumns)

In your example

let originalGrid = [
    [1, 2, 3, 4],
    [1, 2, 3, 4]
  ];
console.log(originalGrid.length) //2
console.log(originalGrid[0].length) //4
console.log(originalGrid[1].length) //4

So in the loop don't forget to add the index:

console.log(originalGrid[i].splice(originalGrid[i].length - numColumns, numColumns))
about 4 years ago · Juan Pablo Isaza Denunciar

0

Write a filter function. Then, you can choose which column "section" to include.

const originalGrid = [
    [1, 2, 3, 4],
    [1, 2, 3, 4]
  ];

const filter = (data, from, to) => data.map(a => a.splice(from, to));

console.log(filter(originalGrid, 0, 2));

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