Skip to content
Advertisement

push even and odd numbers to respective arrays using a for loop

I’m a total beginner and I’m stuck completely on this problem. I’m supposed to use a for loop to traverse an array, pushing odd numbers to the ‘odd’ array, and evens to the ‘even’ array.

No numbers are showing up in my arrays when I test the code. I’ve tried writing it the following two ways:

#1

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

  for (i = 0; i < arr.length; i++) {
    if (arr[i] % 2 !== 0) {
      odd.push();
    } else {
      even.push();
    }
    console.log(arr[i]);
  }
  
  return [odd,even];


#2

function pickIt(arr){
  var odd=[],even=[];
  //coding here
  for (i = 0; i > 0; i++) {
    if (i % 2 !== 0) {
      odd.push();
    } else {
      even.push();
    }
  }
  
  return [odd,even];
}

I’ve checked out some of the solutions to the problem and with respect to the code I’ve got in #2, the most common solution I guess has the for condition written like this:

for (i of arr) 

and then in the if else statement it’s written:

odd.push(i);
even.push(i);

respectively, but I have no idea how people got there especially concerning the ‘for’ bit. Can anyone help my brain understand this?

Advertisement

Answer

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

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 !== 0) {
      odd.push(arr[i]);
    } else {
      even.push(arr[i]);
    }
  }
  
  console.log(odd);
  console.log(even);
}
  
pickIt([10,5,6,3,24,5235,31]);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement