Using the array destructing syntax
In the context of swapping elements in an array, we can use array destructuring to assign the values of the two elements to be swapped to separate variables and then assign them back to their new positions in the array.
In the example below, we will swap the position of the first Element (with Index 0) and the fourth element (with Index 3):
const array = ['A', 'B', 'C', 'D', 'E']; [array, array] = [array, array]; console.log(array);
[ 'D', 'B', 'C', 'A', 'E' ]
As you can see, we only need a single line of code to do the swapping job.
Using a temporary variable
This is a classic technique in programming, and it is quite understandable.
let array = ['A', 'B', 'C', 'D', 'E']; let temp = array; array = array; array = temp; console.log(array);
[ 'A', 'D', 'C', 'B', 'E' ]
Using the Subtraction Method
The subtraction method involves subtracting one element from the other to swap their values. This method only works if the two elements being swapped are numeric values.
const array = [1000, 2000, 3000, 4000]; // swap 2000 and 4000 array = array - array; array = array + array; array = array - array; console.log(array);
[ 1000, 4000, 3000, 2000 ]
If you are a person who likes the beauty of mathematics, this method will suit you.
Using the splice() method
Another possible solution is to use the splice() method, which can remove and insert elements in an array.
let arr = ['sling', 'academy', 'dot com']; // swap first and third elements arr = arr.splice(2, 1, arr); console.log(arr);
[ 'dot com', 'academy', 'sling' ]
All mentioned approaches in this article are decent and concise. However, most developers prefer and use one of the first two methods. How about you? Let us know your opinion by leaving a comment.