Another proper solution?

Tell us what’s happening:

I went a different route than the solutions provided. I used slice to make a shallow copy of the original array, from the start to (not including) index given.

Afterwards used splice normally, mutating the array, starting from index + 1 to get remaining elements. Avoiding the rule of splice-when start is greater than array length function is just adding.

Is this another proper solution? I hope my explanation makes sense.


Window.prototype.tabClose = function (index) {

 var tabsBeforeIndex = this.tabs.slice(0, index); // used slice here
 var tabsAfterIndex = this.tabs.splice(index + 1); // used splice here

 this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // Join them together
 return this;
};



Challenge: Understand the Hazards of Using Imperative Code

Link to the challenge:

It works, but is a bit “hard to reason”.
You make a copy up to an index.
Then change this.tabs using splice.
Then create a new array by concatenating the copy and the modified one.

You could simplify this a lot by just “copy the array but the given index”.
Which can be easily achieved with slice alone.

[...arr.slice(0, index), ...arr.slice(index +1)]

Very common seeing this in JavaScript.
Hope this helps :slight_smile:

wow. That code is beautiful. And thank you.