skip to Main Content

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.

2

Answers


  1. 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]);
    }
    Login or Signup to reply.
  2. Just for fun, here is what you will be able to do one day when you get into more advanced javascript…

    const arr = [22, 33, 44, 55, 66]
    
    const [even, odd] = arr.reduce((a,c)=>(a[c%2].push(c),a),[[],[]])
    
    console.log(odd)
    console.log(even)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search