Search code examples
javascriptsplice

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

  • 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));