0

I can't get a result I wanted:

Even Array is: 2, 18, 38, -10, 0, 104
Odd Array is: 3, 13, -5, 11

Two arrays where one contains even numbers another odd.

Here is the code:

let arrayMain = [2, 3, 13, 18, -5, 38, -10, 11, 0, 104];
let oddArray = [];
let evenArray = [];

for (let i = 0; i < arrayMain.length; i++){
    if (i % 2 == 0) {
        evenArray.push(arrayMain[i]);
    }
    else {
        oddArray.push(arrayMain[i]);
    }
}

console.log("Odd Array is " + oddArray);
console.log("Even Array is " + evenArray);

It gives me:

Odd Array is 3,18,38,11,104
Even Array is 2,13,-5,-10,0

How can I fix this?

2
  • 1
    i is the counter i % 2 will divide divide the array into odd and even places, not odd and even values. You need to do arrayMain[i] % 2 Commented Oct 15, 2020 at 7:50
  • Please add a debugger; inside the code and verify each value and condition. Commented Oct 15, 2020 at 8:02

1 Answer 1

3

You need to check the value, not the index.

if (arrayMain[i] % 2 == 0) {
//  ^^^^^^^^^^ ^
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.