Swapping Items in an Array

by kirupa   |   12 January 2015

Arrays in JavaScript are really powerful, really awesome, and really REALLY funny. If you don't feel that way, that's too bad. They are the primary data structure you have for storing and manipulating collections of data, so you are pretty much stuck with them for a very long time. Despite their importance in the JavaScript world, there is a lot of things they don't support out of the box.

For example, you can't swap two items in an array using the built-in Array methods:

swapping items in an array

I know, right? In this short article, I will show you how to easily swap items in an array.

Onwards!

General Approach for Swapping

Before we jump to the code and actually answer what you are probably here looking for, let's take the scenic route and try to understand how to actually swap items from scratch.

Let's say our array looks as follows:

our example array

What we want to do is swap the item at the (arbitrarily chosen) second index position with the item in the (also arbitrarily chosen) fifth index position:

swap two items

The way to make this happen is to first temporarily store the contents of one of the items we want to swap. For simplicity, let's just choose the first item as the thing we want to store...temporarily:

temp value

With the contents of the first item we want to swap temporarily stored, the next step is to assign the contents of the second item to the first item:

items assigned

Your array is in an awkward state right now with both the items you want to swap storing the same contents. This too is only temporary, for the next step is to take the temporary contents you stored earlier from the first item and assign it to our second item:

almost done

Once that step is complete, you have your final array where the items in the second and fifth index positions are swapped:

the final swap

What we just did is re-create the steps of a swap operation by using a temporary variable and some simple array shenanigans. The code for doing all of this is pretty straightforward, so let's quickly look at that next.

The Code

Finally. We get to the part that you were waiting for. I'm going to provide three variations of a swap implementation for the approach you saw described in the previous section.

One-Off Approach

The first is the direct and lazy approach for a single array whose two items you are interested in swapping:

var myData = ["a", "b", "c", "d", "e", "f", "g"];

var temp = myData[2];
myData[2] = myData[5];
myData[5] = temp;

alert(myData) // a b f d e c g

This approach continues our earlier example by having you swap the contents of the items in the 2nd and 5th index positions.

The Swap Function

For something a bit more reusable, you can use a function whose job it is to swap the items of an array:

var myData = ["a", "b", "c", "d", "e", "f", "g"];

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

swap(myData, 2, 5);
alert(myData); // a b f d e c g

The swap function works by taking three arguments:

  1. The array
  2. The first item whose contents you want to swap
  3. The second item whose contents you want to swap

 When you pass these three arguments in, the end result is that your specified array will get the items at the specified index positions swapped. Yay!

Extending the Array Object

Now, you may find that using a function to do this a bit weird as well. If you believe that a swap method needs to exist and be available for all arrays in your code, then you can actually extend the Array type with your own swap method:

var myData = ["a", "b", "c", "d", "e", "f", "g"];

Array.prototype.swap = function(index_A, index_B) {
    var input = this;

    var temp = input[index_A];
    input[index_A] = input[index_B];
    input[index_B] = temp;
}

myData.swap(2, 5);
alert(myData); // a b f d e c g

To use this approach, just call the swap method directly from your myData array object as shown. The two index positions you pass in will determine which two items will have their contents swapped. For more information on extending objects, check out my appropriately titled Extending Built-in Objects in JavaScript.

Yes, extending built-in objects may be a bad idea!

Some of you probably find the idea of extending a built-in object like Array to be a bad idea. After all, what happens when the swap method on Array is officially implemented or overwritten by a library? These are valid concerns, and ones that you should pay attention to.

Personally, I extend objects all the time, but I give them a more unique name such as kirupaSwap for this case. That greatly reduces the chance of someone else inadvertently stomping over what I've extended.

Conclusion

This entire article could have been written in probably 1/3 the space it ended up taking. With that said, it's good to savor the finer things in life...such as unnecessarily elaborate explanations on how to swap items in an array.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Brought to you by...

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!