Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

354
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!