Swapping even and odd index pairs internally in JavaScript


We are required to write a JavaScript function that takes in an array of literals as the first and the only argument.

Our function should swap each consecutive even index with each other, and swap each consecutive odd indexes with each other.

The function should do these swappings in place.

For example −

If the input array is −

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];

Then the array should become −

const output = [2, 3, 0, 1, 6, 7, 4, 5, 8];

because 0 and 2 gets swapped, 1 and 3 gets swapped, 4 and 6 gets swapped, 5 and 7 gets swapped and finally 8 remains the same.

Example

Following is the code −

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const swapPairs = (arr = []) => {
   const swap = (array, ind1, ind2) => {
      const temp = array[ind1];
      arr[ind1] = arr[ind2];
      arr[ind2] = temp;
   };
   let i = 0;
   for(; i + 3 < arr.length; i += 4){
      swap(arr, i, i + 2);
      swap(arr, i + 1, i + 3);
   };
   if (i + 2 < arr.length){
      swap(arr, i, i + 2);
   };
};
swapPairs(arr);
console.log(arr);

Output

Following is the console output −

[
   2, 3, 0, 1, 6,
   7, 4, 5, 8
]

Updated on: 22-Jan-2021

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements