Matching odd even indices with values in JavaScript


We are required to write a JavaScript function that takes in an array of numbers. The array given as an input to the function have two special properties −

  • The length of the array will always be an even number.

  • The number of even numbers and the number of odd numbers in the array will always be equal (i.e., both being equal to the half of the length of array)

The function should shuffle the elements of the array such that all the even values occupy even indices and all the odd values occupy odd indices.

Note that there may be more than one correct solution to this problem, we are required to find any one of them.

Example

Following is the code −

const arr = [1, 2, 3, 4, 5, 6];
const arrangeToIndices = (arr = []) => {
   let [even, odd] = [0, 1];
   while (even < arr.length && odd < arr.length) {
      if (arr[even] % 2 === 1 && arr[odd] % 2 === 0) {
         [arr[even], arr[odd]] = [arr[odd], arr[even]];
         [even, odd] = [even + 2, odd + 2];
      } else {
         if (0 === arr[even] % 2){
            even += 2;
         };
         if (1 === arr[odd] % 2){
            odd += 2
         };
      };
   };
   return arr;
};
console.log(arrangeToIndices(arr));

Output

Following is the console output −

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

Updated on: 18-Jan-2021

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements