Swap array elements using their index in JavaScript
This post will discuss how to swap array elements using their index in JavaScript.
There are several ways to perform a swap operation on an array in JavaScript. Here are some examples of how to swap two elements in an array given their indices:
1. Using a temporary variable
This is a common technique that works in any version of JavaScript. It involves storing one of the elements in a temporary variable, then assigning the other element to its place, and finally assigning the temporary variable to the other element’s place. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let swapArrayElements = function(arr, indexA, indexB) { // store the first element in a temporary variable let temp = arr[indexA]; // assign the second element to the first element's place arr[indexA] = arr[indexB]; // assign the temporary variable to the second element's place arr[indexB] = temp; }; let arr = [1, 2, 3, 4, 5]; // swap element present at index 1 with index 4 swapArrayElements(arr, 1, 4); console.log(arr); // [1, 5, 3, 4, 2] |
2. Using ES6 Destructuring Assignment
This is a newer feature of JavaScript that allows swapping two elements in an array in one line, without using a temporary variable. It involves using square brackets to assign the elements to each other in a reverse order. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
let swapArrayElements = function(arr, indexA, indexB) { // swap the elements in one line [arr[indexA], arr[indexB]] = [arr[indexB], arr[indexA]]; }; let arr = [1, 2, 3, 4, 5]; // swap element present at index 1 with index 4 swapArrayElements(arr, 1, 4); console.log(arr); // [1, 5, 3, 4, 2] |
3. Using splice() function
This is another way to swap two elements in an array without using a temporary variable, but it is less efficient than the previous functions. It involves using the splice() function to remove and insert elements at the same time. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
let swapArrayElements = function(arr, indexA, indexB) { // remove and insert elements at the same time arr.splice(indexB, 1, arr.splice(indexA, 1, arr[indexB])[0]); }; let arr = [1, 2, 3, 4, 5]; // swap element present at index 1 with index 4 swapArrayElements(arr, 1, 4); console.log(arr); // [1, 5, 3, 4, 2] |
That’s all about swapping array elements in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)