The JavaScript Array.splice() method

If you're into heavy JavaScript development, chances are you'll be running into some serious Array manipulation sooner or later. Luckily, Arrays come packed with a couple of really useful methods. It's somewhat ironic the most useful of these, Array.splice, doesn't work in IE.

What does Array.splice() do?

Array.splice() is used to modify an array, removing a sequence of items and inserting other stuff its place. It does some very cool things when you know how to work with it. Once you get the hang of it you start to find all sorts of uses for it. The notation is like this:

Array.splice( int start, int length, [elements...] );

Meaning: begin at index start, remove length items and (optionally) insert elements. Finally return the removed items in an array. It is best shown through a couple of examples:

var a = [0, 1, 2, 3, 4, 5, 6];
var b = a.splice(1, 3);
> b is now [1, 2, 3]
> a is now [0, 4, 5, 6]

var a = [0, 1, 2, 3, 4, 5, 6];
// You can add as many items as you want
var b = a.splice(1, 3, 'a', 'b'); 
> b is now [1, 2, 3]
> a is now [0, 'a', 'b', 4, 5, 6]

Making it work in IE

I've been trying to write an IE-compatible alternative myself and have been looking online for a while but splice is a tricky beast. Nothing on the internet had a full implementation and I myself found it very hard to get all of the edgy cases right, especially when it comes to inserting new items.

However, for a personal project of mine, a couple of month ago, I really needed it so I sat down and gave it some serious effort. While sitting on the toilet (the best time to relax and think) I came up with the solution: I just needed to write the Array equivalents of String.substr() and String.substring(), then it would be very easy.

if(!Array.prototype.splice) {
    Array.prototype.splice = function(iStart, iLength) {
        if(iLength < 0) iLength = 0;

        var aInsert = new Array();
        if(arguments.length > 2) {
            for(var i=2; i

You need the Array.subarr() and Array.subarray() methods to use this, of course, so if you want to use this get the full source here!.

Edit: Shoot, I just figured it still breaks on values for iStart and iLength that are smaller than zero:

var a = [0, 1, 2, 3, 4, 5];
var b = a.splice(-2, 3, 'a', 'b');
// Native splice:
// a = [0, 1, 2, 3, 'a', 'b'];
// My splice:
// a = ['a', 'b', 1, 2, 3, 4, 5];

The length bug was easy to fix, a matter of enforcing it to be at least zero, but fixing a negative start index will be much harder. It means I have to concatenate the end result differently.

Have something to say about this post? Share your thoughts!