JavaScript Array Move

This post shows how to extend JavaScript Array object with “move” method. The new method accepts two parameters: position 1 and position 2. Array element from position 1 will be moved to position 2 while rest of array will be shifted. Please try the demo.

P F T Array
0 0 – Google Chrome
1 1 – Mozilla Firefox
2 2 – Safari
3 3 – Internet Explorer
4 4 – Opera
5 5 – Netscape
6 6 – SeaMonkey
7 7 – Konqueror
8 8 – Chromium
9 9 – Lynx

Click on “Move” button.

Array.prototype.move = function (pos1, pos2) {
    // local variables
    var i, tmp;
    // cast input parameters to integers
    pos1 = parseInt(pos1, 10);
    pos2 = parseInt(pos2, 10);
    // if positions are different and inside array
    if (pos1 !== pos2 &&
        0 <= pos1 && pos1 <= this.length &&
        0 <= pos2 && pos2 <= this.length) {
        // save element from position 1
        tmp = this[pos1];
        // move element down and shift other elements up
        if (pos1 < pos2) {
            for (i = pos1; i < pos2; i++) {
                this[i] = this[i + 1];
            }
        }
        // move element up and shift other elements down
        else {
            for (i = pos1; i > pos2; i--) {
                this[i] = this[i - 1];
            }
        }
        // put element from position 1 to destination
        this[pos2] = tmp;
    }
}

As you know, the prototype property allows you to add properties and methods to an object. Properties and methods can be added to both prebuilt and custom objects. In this case, “move” method is added to the Array object. Code is simple and allows you to move/shift array members …

5 thoughts on “JavaScript Array Move”

  1. @Larry Battle – Your code is nice, short and it works! What can I say but You learn something new every day. This will surely save someone’s time.
    Thank you!

  2. @Richard Scarrott – Interesting result. It seems that “for loops” and direct access of array members is much faster than internal splice method. Maybe the result implies bad implementation of splice or the problem lies in replacing and returing removed elements of “splice” or the trick is in “if case”. Any other explanation is more then welcome.

    Thank you for creating and sharing this test case.
    Cheers!

    P.S.
    I’m glad that my code performs faster ;)

  3. I always use for loop with arrays. Using splice is a lot of work to me, too lazy for that much effort lol. But this post gave me a good idea on how to use for loop with move.

Leave a Comment