I am looking to iterate through an array starting from the middle and moving outwards.
var array = [a,b,c,d,e];
The desired order of printing would be: c,d,b,e,a
I have managed to divide the array in half and traverse it both forward and backward, but I need to go one element at a time on each side until reaching the end of the array.
If I were to begin from the middle, here is what I have before the loop:
for (var i = Math.floor(array.length/2); i >= 0 || i < array.length; i?){
//Do Something here.
}
Can anyone provide guidance on how to achieve this functionality?
Thank you!
I adapted the answer below and created this function. It allows for starting from any position in the array and selecting the direction to move towards. Although it works, I believe there could be more elegant ways to write this code. It also includes safety measures for incorrect index numbers.
var array = ["a", "b", "c", "d", "e"];
function processArrayMiddleOut(array, startIndex, direction){
if (startIndex < 0){
startIndex = 0;
}
else if ( startIndex > array.length){
startIndex = array.lenght-1;
};
var newArray = [];
var i = startIndex;
if (direction === 'right'){
var j = i +1;
while (j < array.length || i >= 0 ){
if (i >= 0) newArray.push(array[i]);
if (j < array.length) newArray.push(array[j]);
i--;
j++;
};
}
else if(direction === 'left'){
var j = i - 1;
while (j >= 0 || i < array.length ){
if (i < array.length) newArray.push(array[i]);
if (j >= 0) newArray.push(array[j]);
i++;
j--;
};
};
return newArray;
}
var result = processArrayMiddleOut(array, 2, 'left');
alert(result.toString());