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]
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With