Technologies:
Tolerim
a month ago
Struggling with a JavaScript for-loop challenge, trying to sort data in an array.
function findEfficientBulbs(serialNumbers) {
console.log(serialNumbers);
const efficientSerialNumbers = [];
for (let i=0; i<serialNumbers.length; i++) {
if (serialNumbers[i].length === 6 && serialNumbers[i] % 2 !== 0) {
efficientSerialNumbers.push(serialNumbers[i])
}
}
return efficientSerialNumbers;
}
Answers(2)
Vogi
a month ago
Verified Answer
The issue with your code is that the condition serialNumbers[i] % 2 !== 0 is not checking if the number is odd. Instead, it is checking if the remainder of the number divided by 2 is not equal to 0. This means that any number that has a remainder of 1 when divided by 2 will be considered odd, but any number that has a remainder of -1 when divided by 2 will also be considered odd. This is why some even numbers are still being added to the final array.
To fix this issue, you can use the modulus operator % along with an if conditional statement to check if a number is odd or even. Here's an example:
console.log(serialNumbers);
const efficientSerialNumbers = [];
for (let i=0; i<serialNumbers.length; i++) {
if (serialNumbers[i].length === 6 && serialNumbers[i] % 2 === 1) {
efficientSerialNumbers.push(serialNumbers[i])
}
}
return efficientSerialNumbers;
}
In this example, we are checking if the remainder of the number divided by 2 is equal to 1, which means that the number is odd. This should fix the issue and ensure that only odd numbers are added to the final array.
I hope this helps! Let me know if you have any other questions.
Sources
How to Check if a Number is Even or Odd in JavaScriptTesting whether a value is odd or evenHow to determine if a number is odd in JavaScriptJavascript Program to Check if a Number is Odd or EvenTolerim
a month ago
The issue with your code is that serialNumbers[i] % 2 !== 0 only checks for oddness in the last digit of the number, not the entire number itself. To check if a number is odd, you'll need to modify your code to check if the first digit of the number is odd.
Here's an updated version of your function that should work as expected:
function findEfficientBulbs(serialNumbers) {
const efficientSerialNumbers = [];
for (let i=0; i<serialNumbers.length; i++) {
if (serialNumbers[i].length === 6 && Number(serialNumbers[i][0]) % 2 !== 0) {
efficientSerialNumbers.push(serialNumbers[i])
}
}
return efficientSerialNumbers;
}
In this version, we're checking if the first digit of the serial number is odd by using Number(serialNumbers[i][0]) to convert the first digit to a number and checking if it's odd using % 2 !== 0.