Array: Insert an Item at a Specific Index with JavaScript
There are many tasks related to arrays that sound quite simple but (1) aren't and (2) aren't required of a developer very often. I was encountered with one such task recently: inserting an item into an existing array at a specific index. Sounds easy and common enough but it took some research to figure it out.
// The original array var array = ["one", "two", "four"]; // splice(position, numberOfItemsToRemove, item) array.splice(2, 0, "three"); array; // ["one", "two", "three", "four"]
If you aren't adverse to extending natives in JavaScript, you could add this method to the Array prototype:
Array.prototype.insert = function (index, item) { this.splice(index, 0, item); };
I've tinkered around quite a bit with arrays, as you may have noticed:
Arrays are super useful -- JavaScript just makes some tasks a bit more ... code-heavy than they need to be. Keep these snippets in your toolbox for the future!
Man, isn’t this JavaScript powerful…
How about a little step further? Since
splice
takes an indefinite number of arguments, you can do something like this:so you can do
Great tip, thanks. I knew this trick before but I forgot that splice could take more than 2 arguments, phew.
Yes, it’s a very useful function. Last year I was delighted to find out that it exists – it made the project I was working on extremely useful.