Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Trouble with an 'Odd', 'Even' array!

Trying out a Kata where I have to add odd numbers to one array and even numbers to another.

Here's my code so far.

function pickIt(arr){
  var odd=[],even=[];
  //coding here

  for(var i = 0; i < arr.length; i++){
  if (arr  % 2 ) {

      even.push(arr);

  } else {
  odd.push(arr);

  }

  }
    return [odd, even];


}

And here's what the issue appears to be.

Expected: '[[1], [2]]', instead got: '[[[1, 2], [1, 2]], []]' Expected: '[[1, 3], [2]]', instead got: '[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], []]' Expected: '[[3, 1], [2]]', instead got: '[[[3, 2, 1], [3, 2, 1], [3, 2, 1]], []]' Expected: '[[], [10, 20, 30]]', instead got: '[[[10, 20, 30], [10, 20, 30], [10, 20, 30]], []]' Expected: '[[11, 21, 31], []]', instead got: '[[[11, 21, 31], [11, 21, 31], [11, 21, 31]], []]' Expected: '[[1, 5, 1, 1], [8, 4, 6]]', instead got: '[[[8, 1, 5, 4, 6, 1, 1], [8, 1, 5, 4, 6, 1, 1], [8, 1, 5, 4, 6, 1, 1], [8, 1, 5, 4, 6, 1, 1], [8, 1, 5, 4, 6, 1, 1], [8, 1, 5, 4, 6, 1, 1], [8, 1, 5, 4, 6, 1, 1]], []]'

It seems to be printing the array twice and adding a further empty array.

Is the issue with the return statement?

1 Answer

Hi Matt,

The overall structure looks good but you have a few issues.

In your if condition along with when you push to the arrays, you're working with the array itself arr instead of with an individual number from the array which would be arr[i]. So you would need to make that change in those 3 places.

The other thing is that your logic is the reverse of what it should be. You would actually be adding the odd numbers to the even array.

I would suggest you write it like this, arr[i] % 2 == 0

If the remainder is equal to zero then you know you have an even number and you can push it to the even array.