Attempting to remove all even numbers from the array.
I have managed to remove some but there are still two persisting. I am unsure what to do as I have very new to coding and only know the very basics.
function findEfficientBulbs(serialNumbers) {
console.log(serialNumbers);
const efficientSerialNumbers = [];
// Below
//create a loop to go through the array
for (let i = 0; i < serialNumbers.length; i++){
//define a varible to look through the array via loop
const currentBulb = serialNumbers[i]
//create if statement to find odd numbers and has 6 digits
// remove items containing even numbers
if (currentBulb === 6 && currentBulb % 2 === 1 ){
//push variable into efficient array
efficientSerialNumbers.push(currentBulb)
}
}
return efficientSerialNumbers;
}
error I received:
✕ AssertionError: expected [] to deeply equal [ 234567, 456789 ]
logs
[ 123456, 234567, 345678, 456789 ]
I don’t understand why numbers 123456 and 345678 came back.
6
Answers
It seems like you want to remove all even numbers with exactly 6 digits from the
serialNumbers
array and store the remaining odd numbers in theefficientSerialNumbers
array. However, your current code is checking ifcurrentBulb
is equal to 6 and if it’s odd, which is why it’s not working as expected. To fix this issue, you should check if the length of the number is 6 and if it’s odd. Here’s the corrected code:In this code,
currentBulb.toString().length === 6
checks if the length of the number is 6 digits, andcurrentBulb % 2 === 1
checks if it’s an odd number. This should correctly filter out even numbers with 6 digits from the array.If you want to simplify your function, you can use
filter
. And only return anything that isn’t even. Also for length to work, the value needs to be a string not numeric.Remove
currentBulb === 6
from the code and use like below,You can compare the number so it would be between 100000 and 999999 to have it 6 digits long:
Since you are trying to remove the numbers having a length of 6 and the even numbers from an array of numbers, the above code snippet might work well for you. Here the code is filtering out the items from the array by using the above conditions. It will return a new array without the even numbers.
Others here have brilliantly explained the correct way of achieving what you want, but I wanted to help explain what you did wrong.
The crux of the problem lies here:
This statement is essentially saying "currentBulb has the value of 6 AND is an odd number" which will ALWAYS resolve to
false
, and thus always result in an empty array.The error message you got explains this further:
I believe what led you to think that your code just wasn’t removing even numbers was this line:
You printed out your starting array rather than the array that was outputted, which would show all numbers.