1

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!

3
  • "if ((i+2)%2==1) { even.push(arr1[i]);" There's no point to the +2 there at all. Commented Apr 26, 2018 at 13:18
  • The .forEach() gives an index as the second parameter to the callback, so use that instead of x... arr1.forEach((x, i) => { if(i % 2 == 0) { Commented Apr 26, 2018 at 13:20
  • First you have to decide what you mean by "even" and "odd." In your first code block, you seem to be using "even" and "odd" based on the non-technical perception of position (first position = index 0 = odd) rather than the literal evenness/oddness of the index (first position = index 0 = even). But your forEach inverts that. Commented Apr 26, 2018 at 13:20

1 Answer 1

2

The index is passed as the second argument to a forEach callback. You need to replace this:

arr1.forEach(x => {
  if((x) % 2 == 0) {
    even.push(x);
  } else {
    odd.push(x);
  }
});

by this:

arr1.forEach((x, i) => {
  if(i % 2 == 0) {
    even.push(x);
  } else {
    odd.push(x);
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

I'll accept the answer but it won't let me do it right away, I have to wait 9 minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.