How to use swapping without extra array In Javascript

To move an array element without an extra array, use array destructuring and swapping. Specify the indices to swap, and swap their values directly using destructuring assignment. This efficiently rearranges the array elements without creating a new array.

Example: In this example we swaps the elements at indexFrom and indexTo in the array using destructuring assignment, effectively moving the element at index 2 to index 1, then logs the modified array to the console.

JavaScript
const array = [1, 2, 3, 4, 5];
const indexFrom = 2; // Index of element to move
const indexTo = 1; // New index for the element

[array[indexFrom], array[indexTo]] = [array[indexTo], array[indexFrom]]; 
console.log(array); 

Output
[ 1, 3, 2, 4, 5 ]


How to move an array element from one array position to another in JavaScript?

In JavaScript, we can access an array element as in other programming languages like C, C++, Java, etc. Also, there is a method called splice() in JavaScript, by which an array can be removed or replaced by another element for an index. So to move an array element from one array position to another we can splice() method or we can simply use array indexing ([]). 

These are the following ways to solve this problem:

Table of Content

  • Using for loop
  • Using splice() function
  • Using slice(), concat(), and spread operator
  • Using swapping without extra array

Similar Reads

Using for loop

In this approach, we are using a for loop for moving an array element from one position to another one....

Using splice() function

In this approach, we are using splice() function. If the given posiiton is less then zero then we will move that element at the end of the array. If it is greater than 0 then we will move the element in between the array, that is how we move our element according to the index....

Using slice(), concat(), and spread operator

In this approach, we are using slice(), concat(), and spread operator. we are craeting the array from the index 0 to the index where that element(that will be moved) is present and the inserted new element and the remaining elements....

Using swapping without extra array

To move an array element without an extra array, use array destructuring and swapping. Specify the indices to swap, and swap their values directly using destructuring assignment. This efficiently rearranges the array elements without creating a new array....