Running Turtle Running Turtle - 1 month ago 7
CoffeeScript Question

split an array into two arrays based on odd/even position

I have an array

Arr1 = [1,1,2,2,3,8,4,6]
.

How can I split it into two arrays based on the odd/even-ness of element positions?

subArr1 = [1,2,3,4]
subArr2 = [1,2,8,6]

Answer

You could try:

var Arr1 = [1,1,2,2,3,8,4,6],
    Arr2 = [],
    Arr3 = [];

for (var i=0;i<Arr1.length;i++){
    if ((i+2)%2==0) {
        Arr3.push(Arr1[i]);
    }
    else {
        Arr2.push(Arr1[i]);
    }
}

console.log(Arr2);

JS Fiddle demo.