Reorder an Array in Specific Pattern

Problem Statement

Reorder an Array in such a way that each element from the mid of array replaces the 2nd index alternatively.

If you want to reorder the elements in the nums array in a specific way (in this case, alternating between the first half and the second half), you can achieve this by creating two separate arrays for the first half and the second half of the input array, and then interleave their elements. Here’s how you can do it in JavaScript:

// We have the array given as:
const nums = [11, 12, 13, 14, 15, 21, 22, 23, 24, 25];

// Declaring function that will take the array and change the order of it
function shuffleArray (arr) {
  	// Dividing the array into two parts
    let leftSide = nums.slice(0, 5);
    let rightSide = nums.slice(5);

    const reordered = [];
    for (let i = 0; i< leftSide.length; i++) {
        reordered.push(leftSide[i]);
        reordered.push(rightSide[i]);
    };
    return reordered;
};

// Calling function and passing the array as argument
shuffleArray(nums);

In this code, the reorderArray function takes an input array nums, separates it into two halves (firstHalf and secondHalf), and then interleaves their elements into the reorderedNums array. The output will be [11, 21, 12, 22, 13, 23, 14, 24, 15, 25] based on the given nums array.

Happy Coding!

You May Also Like

More From Author