How to swap two array elements in JavaScript

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.

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).

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.

2. Using array destructuring

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

3. Using splice method

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

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..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *