re: JavaScript Array Splice Issue VIEW POST

FULL DISCUSSION
 

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

I would use

const arr = ['one', 'two', 'three', 'four', 'five'];
const newArr = arr.filter(item => item !== name);
 

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

code of conduct - report abuse