JavaScript Array Splice Issue

bob.ts - Aug 15 '19 - - Dev Community

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 one with a quick fix that took me several hours to track down what was going on.

Now that I've seen the answer, it's obvious ... at the time I was seeing the issue, it was frustrating to say the least.

Finding a good way to query the issue (couldn't come up with good search terms) led me to creating this article.

I wrote the following code ...

triggerDelete: async (name) => {
  let stored = ['one', 'two', 'three', 'four', 'five'];
  stored = stored.splice(stored.indexOf(name), 1);
  return stored;
}
Enter fullscreen mode Exit fullscreen mode

I've simplified it some. The issue was simple, when I passed in 'two' the array returned was ...

triggerDelete('two');

/*
 * returns ['two'], not ['one', 'three', 'four', 'five']
 */
Enter fullscreen mode Exit fullscreen mode

I expected ['one', 'three', 'four', 'five'] to be the array returned.

... after two hours of searching and finally asking for a second pair of eyes, the solution was ...

triggerDelete: async (name) => {
  let stored = ['one', 'two', 'three', 'four', 'five'];
  stored.splice(stored.indexOf(name), 1);
  return stored;
}
Enter fullscreen mode Exit fullscreen mode

Quite simply, the issue was that I was not changing the array, I was assigning the result of the splice back into the stored variable; hence, ['two'] ...

Hopefully this article will save someone else some of the pain I felt down the road!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .