skip to Main Content

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


  1. This will always be false for numeric values:

    currentNumber.length === 6
    

    Because numbers don’t have a length property, so that value is undefined.

    You can convert the number to a string first:

    currentNumber.toString().length === 6
    

    Or, as pointed out in a comment below, you could check the value of the number against upper and lower bounds:

    currentNumber > 99999 && currentNumber < 1000000
    

    (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:

    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.toString().length === 6) {
          efficientSerialNumbers.push(currentNumber)
        }
      };
      return efficientSerialNumbers;
    }
    
    console.log(findEfficientBulbs([ 123456, 234567, 345678, 456789 ]));
    Login or Signup to reply.
  2. Simpler

    const findEfficientBulbs = (serialNumbers) => serialNumbers
      .filter(num => num % 2 === 1 && num >= 100000 && num <= 999999);
    
    console.log(findEfficientBulbs([123456, 234567, 345678, 456789]));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search