How to swap array elements in JavaScript

In this tutorial, let us look at how to swap array elements in JavaScript.

We’ll start off by taking things easy, while moving on to using more pre-defined JavaScript methods as we dive deep into the topic.

We’ll look at:

1. Using temporary variables to swap the array elements
2. Using the splice method
3. Using the slice method
4. Using destructuring
5. Using addition and subtraction with numeric values, and finally,
6. Using the sort() and reverse() methods

So, let’s get into it then!

Using temporary variables to swap array elements in JavaScript

To start with, we’re going to be looking at using a temporary variable to make the swap.

The process works like this:

1. Store the first element’s value in the temporary variable.
2. Assign the value of the second element to the first element.
3. Assign the value of the temporary variable (which contains the first element’s original value) to the second element.

This way, we’ve effectively swapped the values of the two elements. Look at the example below:

const swapElements = (arr,index1,index2) => {
    let temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;
    return arr;

let arr = [10,15,20,25,30];
console.log(swapElements(arr,0,4)); // [30, 15, 20, 25, 10] 

As you can see, we’ve used a function that accepts the array and the two indices whose values need to be swapped.

We’ve created a temp variable, performed the swap, and returned the modified array.

This method works with any kind of swapping inside the array, as long as you have the 2 indices you want to work with.

Using the splice method

You can also use the splice method to remove the first element from the array while replacing that ‘space’ with the second element’s value; then, retrieve the first element’s value and place it where the second element is.

Look at the example below. I’ve first given an example of the splice method. This method can be used to remove and replace elements from the given position.

We’ve given the position as 0 (first element) and the number of elements to be removed from that position as 1 (to just remove the first element). The next few arguments hold the values that need to replace the removed values.

Since we’re removing only 1 value, we’re replacing that with another value (5).

Now, if you print the result of the splice operation, you’ll see that you get the removed item in a new array.

If you print the array on the other hand, you would have gotten [5,15,20,25,30], as we needed.

This is what we’re going to be using to swap our values.

let arr = [10,15,20,25,30];
console.log(arr.splice(0, 1, 5)); //[10] 

To start with, we’re going to splice our array, and make sure it removes just the arr[index1] value by starting from index1 and giving the number of items to remove as 1.

Replace that value with the value inside arr[index2] so now the array has been modified in such a way that both arr[index1] and arr[index2] hold the same value that was originally in arr[index2].

Finally, right after that, tag along a [0]. As you know, splice operations don’t just modify the array, they also return the value(s) that were removed in a new array. Since we removed only one value, we can just access the first element to retrieve the value that was originally in arr[index1].

Now, assign this value to arr[index2] and you’ve successfully swapped both values.

arr[index2] = arr.splice(index1, 1, arr[index2])[0]; 

This method works regardless of the position of the two elements you want to swap.

Using destructuring

You can also use array destructuring to change the values. [arr[index1],arr[index2]] will access both those elements so just those two can be assigned new values.

Now, all you must do is assign [arr[index2],arr[index1]] to those so the values are swapped, as shown below:

[arr[index1], arr[index2]] = [arr[index2], arr[index1]]; 

Using the slice method

You can also use the ‘slice’ method to do the swapping, but you might have to go about things in a roundabout way and use the help of other methods.

Also, the ‘slice’ method doesn’t directly modify the original array, but just creates a copy of the ‘sliced’ array, so you need to re-assign the new array back into the original array’s variable to complete the swap.

Use the spread operator with the slice method

You can use the ‘spread’ operator with the ‘slice’ method to achieve the swapped result you want. Look at the example below:

let arr = [10,15,20,25,30];

arr = [arr[arr.length-1], ...arr.slice(1,arr.length-1), arr[0]];
console.log(arr); // [30, 15, 20, 25, 10] 

As you know, the ‘spread’ operator can be used to spread the values of an array, so the individual elements can be copied to another array. That’s what we’re doing here, though we’re just re-assigning the newly formed array back to ‘arr’.

In this example, we’re swapping the first and last elements’ values, which hold the indices 0 and arr.length-1 respectively.

So naturally, in the newly formed array, the first element would now have arr[arr.length-1] as its value, indicating the last element’s value, and the last element would have arr[0] as the value, indicating the first element’s value.

In between, we need the rest of the elements. The ‘slice’ method is the best way of getting these values. It can be used to slice a portion of an array and take it out to be used for our purposes; in this case, that is to fill the gap between the first and last values.

This method’s first argument refers to the first position of the slice and the last argument refers to the position after the last position of the slice (as in, the second argument’s position is not included).

So, if we slice from 1 to arr.length-1, we’re slicing from the 2nd element in the array till the second last element (arr.length-1 refers to the last element’s position, which is not included in the slice).

But we can’t just directly place the sliced array inside the new array. That’ll just create a reference to the array, when in fact we want access to its individual elements.

That’s where the ‘spread’ operator comes in. After the slice, you can use the spread operator to get the individual elements and place it in the new array and you’re good to go.

Use the concat method with the slice method

You can also use the ‘concat’ method instead of just creating an array. For this method, the first element arr[arr.length-1] comes first, and then .concat. Then inside the parenthesis, you can add as many elements as you want.

In our case, we’ll be adding our ‘spread’ sliced array and the last element, which is arr[0], as shown below:

arr = [arr[arr.length-1]].concat(...arr.slice(1,arr.length-1), arr[0]); 

Using addition and subtraction

If your array is made up of just numbers, then you can use addition and subtraction to arrive at the swapped result. Look at the example below:

const swapElements = (arr,index1,index2) => {
    arr[index1] = arr[index1] + arr[index2]; //arr[0] = 40
    arr[index2] = arr[index1] - arr[index2]; //arr[4] = 40-30 = 10
    arr[index1] = arr[index1] - arr[index2]; //arr[0] = 40 - 10 = 30
    return arr;

As you can see,

1. We added both the values and assigned it to the first element for the first step. (10 + 30 = 40)
2. Then, the second element was assigned the subtracted value of both the elements, which gives us the original value of the first element (40 – 30 = 10, which was the original value of the 1st element)
3. Then, the first element was assigned yet another subtracted value between both the elements, which would give us back the original value of the second element (40 – 10 = 30).

Ultimately, we’ve swapped both values.

Unfortunately, this method doesn’t work when the values are not numbers, or any value on which mathematical operations cannot be performed.

Reversing the values in descending order

There are also some pre-defined methods that can be used to just sort the array values in ascending or descending values. That does not solve our problem exactly, but if this kind of ordering is what you need, go ahead with these methods.

The reverse method

The ‘reverse’ method, as the name implies, sorts the values in an array in the descending order, as shown below:

console.log(arr); //  [30, 25, 20, 15, 10] 

The sort method

The ‘sort’ method can be used to sort the values of an array in multiple ways, but in this example, we’re doing a descending order sort.

To do that, every two values in the array (the current value and the next for every iteration) needs to be subtracted and applied to the current element, as shown below:

arr = arr.sort((a, b) => b - a); // ( a - b) will do ascending order reverse

console.log(arr); //  [30, 25, 20, 15, 10] 

That’s it! We’ve looked at how to swap the array elements in JavaScript in different ways.

Leave a Comment