Swapping two array elements in a single line using JavaScript
In JavaScript, there exist many ways by which one can swap two array elements. In this article, we will discuss a way in which one can swap two array elements in JavaScript in a single line. The input and output would be as follows.
Input: arr = { 10, 20, 40, 30 }
Output: arr = { 10, 20, 30, 40 }
// Swapped 30 and 40
Here are some common approaches:
Table of Content
Using Destructuring Method
This is a far better method than anyone. This method can be executed in a single line. This swapping can be done by writing the 2 array elements and want to reverse in order and in square brackets on the left-hand side. On the right-hand side, we will write the same array elements but this time in reverse order. We can also create a reusable function that can swap the specified index of the array.
Syntax:
[a[m], a[n]] = [a[n], a[m]]
// Where m and n are the index numbers to swap
Example 1: In this example, we will swap two number array elements in a single line using JavaScript.
let arr = [1, 2, 3, 5, 4];
// Swapping element at index 3 with
// index 4
[arr[3], arr[4]] = [arr[4], arr[3]];
// Print the array
console.log(arr);
Output
[ 1, 2, 3, 4, 5 ]
Example 2: In this example, we will swap two string array elements in a single line using JavaScript.
let arr = ["e", "b", "c", "d", "a"];
// Swapping element at index 0 with
// index 4
[arr[0], arr[4]] = [arr[4], arr[0]];
// Print the array
console.log(arr);
Output
[ 'a', 'b', 'c', 'd', 'e' ]
Using XOR Bitwise Operator
Using the XOR bitwise operator, you can swap two elements without a temporary variable. This is done by sequentially applying XOR operations to the elements. This works because XORing a number twice with the same number returns the original number, effectively swapping the values.
Example: In this example we swaps the elements at index1 and index2 in the array arr using the XOR bitwise operator.
let arr = [1, 2, 3, 4, 5];
let index1 = 1;
let index2 = 3;
arr[index1] ^= arr[index2];
arr[index2] ^= arr[index1];
arr[index1] ^= arr[index2];
console.log(arr);
Output
[ 1, 4, 3, 2, 5 ]
Using Array.splice
Using Array.splice, remove the elements to be swapped from the array, then insert them back into their new positions. This method effectively swaps the elements in place without needing additional temporary variables.
Example :
let array = [1, 2, 3, 4];
array.splice(0, 2, ...array.slice(1, 3), array[0]);
console.log(array); // [2, 1, 3, 4]
Output
[ 2, 3, 1, 3, 4 ]