Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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]
like image 526
Running Turtle Avatar asked Nov 14 '11 10:11

Running Turtle


People also ask

How do you split an array into two?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

How do you separate even and odd numbers in JavaScript?

log(seperateArray(numbers)); This works by using the modulo '%' sign which returns the remainder after dividing a number. So in this case, all odd numbers divided by 2 would return a remainder of 1 and all even numbers would return 0.


2 Answers

odd  = arr.filter (v) -> v % 2
even = arr.filter (v) -> !(v % 2)

Or in more idiomatic CoffeeScript:

odd  = (v for v in arr by 2)
even = (v for v in arr[1..] by 2)
like image 140
Ricardo Tomasi Avatar answered Oct 07 '22 07:10

Ricardo Tomasi


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.

like image 32
David Thomas Avatar answered Oct 07 '22 08:10

David Thomas