Linked Questions

Popular Questions

Interweave an array's values in place using JavaScript

Asked by At

let's say I have an array of numbers => [1,2,3,4,5,6]

and I want to interweave them => [1,4,2,5,3,6]

I can do that with the following code

const nums = [1,2,3,4,5,6];
const results = [];
nums.slice(0, nums.length / 2).forEach((num, index) => results.push(num, nums.slice(nums.length / 2, nums.length)[index]))
console.log(results);

to be a better programmer overall, I'd like to know how to modify the array in place as if it were a linked list and without having to create any additional space complexity by having an additional array.

I've written out the logic, but I can't seem to find a pattern to create a function off of.

// [0] do nothing

// [1]
currentIndex = 1;
temp = nums[3];
nums[3] = nums[currentIndex];
nums[currentIndex] = temp;
// 1[2]3[4]56 => 1[4]3[2]56

// [2]
currentIndex = 2;
temp = nums[3];
nums[3] = nums[currentIndex];
nums[currentIndex] = temp;
// 14[3][2]56 => 14[2][3]56 

// [3]
currentIndex = 3;
temp = nums[4];
nums[4] = nums[currentIndex];
nums[currentIndex] = temp;
// 142[3][5]6 => 142[5][3]6

// while (currentIndex < nums.length / 2) {...}

am I overthinking this?

Related Questions