I am trying to push every element in an array that is on a odd position to an array and the same with elements in even positions. For example:
var arr = [a, b, c, d, e, f, g];
//Would give me this
var odd = [a, c, e, g];
var even = [b, d, f];
I have a code that works with a for loop and it looks like this:
for (var i=0;i<arr1.length;i++){
if ((i+2)%2==1) {
even.push(arr1[i]);
} else {
odd.push(arr1[i]);
}
}
but instead of using a for loop I want to use a forEach loop. This is what I did:
var arr1 = [1,1,2,2,3,8,4,6];
arr1.forEach(x => {
if((x) % 2 == 0) {
even.push(x);
} else {
odd.push(x);
}
});
but this doesn't work, instead of outputing this:
even = [ 1, 2, 8, 6 ];
odd = [ 1, 2, 3, 4 ];
It outputs this, which is wrong:
even = [ 2, 2, 8, 4, 6 ];
odd = [ 1, 1, 3 ];
So instead of ouputing the element that is in a odd or even position in the array it outputs the elements that are odd or even.
Thanks in advance!
if ((i+2)%2==1) { even.push(arr1[i]);" There's no point to the+2there at all..forEach()gives an index as the second parameter to the callback, so use that instead ofx...arr1.forEach((x, i) => { if(i % 2 == 0) {forEachinverts that.