Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Swapping Items in an Array

by kirupa   |    filed under Arrays

Did you know that there is no built-in way to swap two items in an array? In this article and video, you'll learn how to fix that!

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!

Kirupa's book on Arrays

The Perfect Book to Learn About Arrays

To kick your array skills into the stratosphere, everything you need to be an arrays expert is available in this book.

BUY ON AMAZON

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:

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

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

console.log(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:

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

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

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

swap(myData, 2, 5);
console.log(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:

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

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

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

myData.swap(2, 5);
console.log(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.

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2024 //--