Swap two array elements in JavaScript
In this short post, we are going to see about how to swap two array elements in JavaScript. Here, I have listed some methods that I’ve learnt to swap two array elements.
This is the array we going to use as an example.
let a = ['a', 'b', 'c', 'e', 'd']
1. Temporary Variable
Suppose we want to swap the elements in the index 2 and 3, we can use a temporary variable.
let tmp = a[4]; a[4] = a[3]; a[3] = tmp; //[ 'a', 'b', 'c', 'd', 'e' ]
2. Assignment Operator
Another option without the temporary variable, is to use this syntax:
const a = ['a', 'b', 'c', 'e', 'd']; [a[3], a[4]] = [a[4], a[3]]; //[ 'a', 'b', 'c', 'd', 'e' ]
3. Using splice()
method
Here is an another way to swap the array elements.
var swapArrayElements = function (a, x, y) { if (a.length === 1) return a; a.splice(y, 1, a.splice(x, 1, a[y])[0]); return a; }; swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]
4. Non-Mutative Method
This method will never change the original array. ES6y
version
const swap = (arr, index1, index2) => arr.map((val, idx) => { if (idx === index1) return arr[index2]; if (idx === index2) return arr[index1]; return val; }); const foo = [1, 2, 3, 4, 5]; const swapped = swap(foo, 1, 3); console.log(foo); //=> [1, 2, 3, 4, 5] console.log(swapped); //=> [ 1, 4, 3, 2, 5 ]