Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating separate arrays for even and odd numbers

This is beginner level. I am trying to create separate arrays for odd and even numbers from the parent array. Below the code:


const arr = [22, 33, 44, 55, 66]
let even = []
let odd = []



function separateArray(arr) {

    let j, k

    for( let i = 0; i < arr.length; i++ ) {

        if( arr[i]%2 === 0 ){

            even[j] = arr[i]
            j++

        }else {

            odd[k] = arr[i]
            k++

        }
        
    }   
}

separateArray(arr)

for( let i = 0; i < even.length; i++ ) {

    console.log(even[i])

}

I tried calling the function separateArray and then log the even numbers in the console. But it doesn’t display anything.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason why you are not seeing anything in the console is because you have not initialized the values of j and k.
In JavaScript, accessing an undefined variable will result in a ReferenceError. You need to initialize j and k to 0 before using them as array indices:

const arr = [22, 33, 44, 55, 66];
let even = [];
let odd = [];

function separateArray(arr) {
  let j = 0,
    k = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
      even[j] = arr[i];
      j++;
    } else {
      odd[k] = arr[i];
      k++;
    }
  }
}

separateArray(arr);

for (let i = 0; i < even.length; i++) {
  console.log(even[i]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading