Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process array from the middle out

I need to go through an array from the middle outwords.

var array = [a,b,c,d,e];

I would need to print in this order: c,d,b,e,a

I have already split the array in half, first going forward and then going backwards which is already an improvement, but I really need to go one on each side till the end of the array on each side.

Say I want to start in the middle. I have the following before the loop statement, condition, and I can't seem to figure out the third part to switch one on each side incrementally.

for (var i = Math.floor(array.length/2); i >= 0 || i < array.length; i?){
//Do Something here.
}

Does anyone know how to do this? Obviously I can't seem to test this in this condition.

Thanks

I modified the answer below (Thanks so much) to come up with this function. It allows to start from anywhere in the array and choose the direction to go. I am sure it could be written more elegantly. There is also a safety for wrong 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());

http://jsfiddle.net/amigoni/cqCuZ/

like image 564
Leonardo Amigoni Avatar asked Oct 17 '12 15:10

Leonardo Amigoni


1 Answers

Two counters, one going up, other going down:

var array = ["a", "b", "c", "d", "e"];
var newArray = [];

var i = Math.ceil(array.length/2);
var j = i - 1;

while (j >= 0)
{
    newArray.push(array[j--]);
    if (i < array.length) newArray.push(array[i++]);
}

http://jsfiddle.net/X9cQL/

like image 94
st3inn Avatar answered Oct 12 '22 01:10

st3inn