DEV Community

Discussion on: JavaScript Array Splice Issue

Collapse
 
emnudge profile image
EmNudge

Array in-place mutation gets really annoying at times for this very reason.
Many array methods are a toss up between returning a new array and mutating the old one.

Here is a quick list of array methods that mutate in place. All other array methods do not.

  • Array.prototype.pop()
  • Array.prototype.push()
  • Array.prototype.shift()
  • Array.prototype.unshift()
  • Array.prototype.reverse()
  • Array.prototype.sort()
  • Array.prototype.splice()

When dealing with removing an item from the array, I generally like to do an immutable version for the reason described above in the post. So instead of

const arr = ['one', 'two', 'three', 'four', 'five'];
arr.splice(arr.indexOf(name), 1);
Enter fullscreen mode Exit fullscreen mode

I would use

const arr = ['one', 'two', 'three', 'four', 'five'];
const newArr = arr.filter(item => item !== name);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rfornal profile image
bob.ts

Excellent information ... now to retrain an old brain to remember the .filter ... Thanks!