Splice an array without mutating it

Darren Jones
April 27, 2021

The `Array.prototype.splice()` method is a versatile method, but it mutates the array that calls it. This is an alternative function that returns a new array instead:

copy code
javascript
const splice = (array, start, count, ...params) => [...array.slice(0, start), ...params, ...array.slice(start+count)]
  
  const food = ['🍏','🍌','🥕','🍩']
  const letThemEatCake = splice(food,0,3,'🧁','🍰')
  
  console.log(letThemEatCake)
  // ["🧁","🍰","🍩"]

This uses the 'Array.prototype.slice()' method to create a copy of the array up to, but not including, the 'start' parameter and places this sub-array into a new array using the spread operator. Any extra values that are entered after the first 3 arguments are collected in an array called 'params', these are then inserted into the middle of the array to be returned using the spread operator, finally we add the last section of the array that comes 'count' places after the index specified by the 'start' parameter.

Note that this method returns a copy of the original array and not the sub-array that was removed, which is what 'Array.prototype.splice()' returns.

Know a better answer? Join our our community and let us know.