DEV Community

Cover image for JavaScript Array Splice Issue

JavaScript Array Splice Issue

bob.ts on August 15, 2019

This is an issue that cropped up for me today: I was splicing a name out of an array and was getting the wrong result back. The issue was a simple ...
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!

Collapse
 
clarity89 profile image
Alex K.

When I get issues like this, the first thing I do is go to MDN and check what's the return value of the mehtod Im using is (or if there's any at all) :)

Collapse
 
rfornal profile image
bob.ts

Yeah ... I should be thinking that route. I struggled with finding a good set of search terms to describe my issue. This method usually works extremely well for me.

I'll definitely keep your idea in mind for the next time I get bogged down like this!

Thanks!

Collapse
 
chiangs profile image
Stephen Chiang

You could use slice instead too.

Collapse
 
rfornal profile image
bob.ts

Absolutely ... this was just the issue I had at the time.