Clue Mediator

How to swap two array elements in JavaScript

📅May 2, 2022

In this article, we’ll show you how to swap two array elements in JavaScript. There are multiple ways to swap two array elements using JavaScript but we will look at best three of them.

Checkout more articles on JavaScript

Example:

Suppose we have the following array. In this scenario, we wish to exchange the element at index 5 (`f`) with the element at index 2 (`c`).

const arr = ['a', 'b', 'c', 'e', 'd', 'f'];

Ways to swap two array elements in JavaScript

  1. Using temporary variable
  2. Using array destructuring
  3. Using splice method

1. Using temporary variable

We can use the temporary `temp` variable to swap the elements. Look at the following code.

const temp = arr[2];
arr[2] = arr[5];
arr[5] = temp;

console.log(arr); // ['a', 'b', 'f', 'e', 'd', 'c']

2. Using array destructuring

Array destructuring was introduced in ES2015, allowing you to write it like this.

[arr[2], arr[5]] = [arr[5], arr[2]];

console.log(arr); // ['a', 'b', 'f', 'e', 'd', 'c']

3. Using splice method

Let’s use the splice method to swap the values.

Array.prototype.swapItems = function(a, b) {
    this[a] = this.splice(b, 1, this[a])[0];
    return this;
}

arr.swapItems(2, 5);

console.log(arr); // ['a', 'b', 'f', 'e', 'd', 'c']

After using any of the above methods, array `arr` will be correctly ordered as we want.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂