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.
>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]);
}