Array: Insert an Item at a Specific Index with JavaScript

By  on  

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!

Recent Features

  • By
    5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

  • By
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

Incredible Demos

  • By
    Dynamically Load Stylesheets Using MooTools 1.2

    Theming has become a big part of the Web 2.0 revolution. Luckily, so too has a higher regard for semantics and CSS standards. If you build your pages using good XHTML code, changing a CSS file can make your website look completely different.

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Discussion

  1. Man, isn’t this JavaScript powerful…

  2. MaxArt

    How about a little step further? Since splice takes an indefinite number of arguments, you can do something like this:

    Array.prototype.insert = function (index) {
      this.splice.apply(this, [index, 0].concat(this.slice.call(arguments, 1)));
    };
    

    so you can do

    array.insert(2, "three", "another three", "the last three");
    array;  // ["one", "two", "three", "another three", "the last three", "four"]
    
  3. Great tip, thanks. I knew this trick before but I forgot that splice could take more than 2 arguments, phew.

  4. 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.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!