Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ]

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading