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

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

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 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!