I’m currently beginning a Javascript coding course. One task requires me to check if a serial number is valid, and if it is, add it to an array to store all valid serial numbers.
The serial numbers must be:
- odd numbers
- contain 6 digits
Here is my current code:
function findEfficientBulbs(serialNumbers) {
console.log(serialNumbers);
const efficientSerialNumbers = [];
for (let i = 0; i < serialNumbers.length; i++) {
let currentNumber = serialNumbers[i]
if (currentNumber % 2 === 1 && currentNumber.length === 6) {
efficientSerialNumbers.push(currentNumber)
}
};
return efficientSerialNumbers;
}
According to the platform, this code is not removing the even numbers, error message below:
‘should keep all efficient numbers – those that are odd and have six
digits in✕ AssertionError: expected [] to deeply equal [ 234567, 456789 ]
logs
[ 123456, 234567, 345678, 456789 ]’
Have tried as above, as well as nested If statements
2
Answers
This will always be
false
for numeric values:Because numbers don’t have a
length
property, so that value isundefined
.You can convert the number to a string first:
Or, as pointed out in a comment below, you could check the value of the number against upper and lower bounds:
(For large sets this could potentially have a performance improvement as well. For small sets it’s more a matter of personal preference.)
For example:
Simpler