How can serial numbers be sorted using a JavaScript If Statement based on 2 criteria?

I'm currently enrolled in a JavaScript coding course where I am tackling a task involving validating serial numbers. The requirement is to check if a serial number is valid and then add it to an array to store all the valid serial numbers. The criteria for a valid serial number are as follows:

  • It must be an odd number
  • It must have exactly 6 digits

Below is my current code snippet:

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;
}

However, after testing my code on the platform, I received an error message indicating that the even numbers were not being removed. Here is the specific error message:

'should keep all efficient numbers - those that are odd and have six digits'

✕ AssertionError: expected [] to deeply equal [ 234567, 456789 ]

logs

[ 123456, 234567, 345678, 456789 ]'

I have attempted using nested if statements but still faced the same issue.

Answer №1

In the case of numeric values, this statement will always evaluate to false:

currentNumber.length === 6

This is because numbers do not possess a length property, resulting in an undefined value.

To address this, you can first convert the number into a string:

currentNumber.toString().length === 6

Alternatively, as suggested in a comment below, you can compare the numerical value against specified upper and lower limits:

currentNumber > 99999 && currentNumber < 1000000

(In cases involving sizable datasets, this approach might offer performance enhancements. For smaller datasets, it may simply boil down to individual preference.)

For instance:

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

Answer №2

More Streamlined

const findOptimalLamps = (serialNumbers) => serialNumbers
  .filter(num => num % 2 === 1 && num >= 100000 && num <= 999999);

console.log(findOptimalLamps([123456, 234567, 345678, 456789]));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript Truthy and Falsy Tutorial on Codecademy

Could someone kindly clarify why this code is not functioning correctly? let defaultName; if (username) { defaultName = username; } else { defaultName = 'Stranger'; } This code snippet was found in the JavaScript section on Codecademy, but a ...

Information backed by the HTML5 Local Storage feature

Is it possible to use a Local Storage object to store another Local Storage object? Thank you in advance. ...

Tips for efficiently loading data into a vuex module only when it is required and addressing issues with async/await functionality

Is there a method to load all the data for a Vuex store once and only load it when necessary? I believe there is, but I am having trouble implementing it. I'm not sure if it's due to my misunderstanding of Vuex or Async/Await in Javascript promi ...

Determining if a replacement took place in the Javascript replace function

I've developed a function that scans through a set of strings and replaces specific patterns: var content = 'Here is a sample string 1/23'; var currentDate = new Date(); var currentMonth = currentDate.getMonth()+1; var currentDay = curre ...

Nodes in force-directed graphs are magnetically attracted to the central point

After finding a solution to the issue in this question Insert text inside Circle in D3 chart I have encountered an unexpected behavior where my nodes are not positioned correctly. I am unsure about which property is controlling the x and y coordinates of ...

Using Jquery to access the grandparent element

When I have code similar to what is shown below, an element contains within 3 layers: <span class="dropdown test1"> <span class="test2" type="button" data-toggle="dropdown">hello</span> <ul class="dropdown-menu test3" style="m ...

Extracting the magnifying glass from the picture

After implementing a function to add a magnifying glass (.img-magnifier-glass) on button click, I am now looking to remove the glass by clicking the "cancel" button. However, I am unsure of how to write this function to interact with the "magnify" function ...

Automatically redirect to a different page upon clicking the jquery popup button

I integrated a jQuery popup feature on my website to display messages. Now, I am looking to implement a redirect to another page when the user clicks a button within the jQuery popup. However, I am unsure of how to achieve this. <script type="text/ja ...

Steps to retrieve the latest value of a specific cell within the Material UI Data Grid

After updating the cell within the data grid, I encountered an issue where I could retrieve the ID and field using the prop selectedCellParams, but retrieving the modified value was proving to be challenging. In order to successfully execute the PUT reque ...

Unable to prepend '1' to the list

My goal is to display a list as '1 2 3...', but instead it is showing '0 1 2...' var totalLessons = $('.lesson-nav .mod.unit.less li').length; for (var i = 0; i < totalLessons; i++) { $('.lesson-nav .mod.unit.les ...

Submit data in the manner of a curl request

Instead of using a curl command to push a file to a web server, I am attempting to create a simple webpage where I can select the file and submit it. Here is the HTML and JavaScript code I have written for this purpose: <html> <body> <i ...

The issue of app.css and app.js resources not loading in Laravel 8 with nginx, resulting in a 404 not found error, needs to be

Although this question may appear to be a duplicate, I assure you it is different. I have thoroughly searched through Stack Overflow, Laracast, Reddit, and GitHub for a solution. My setup includes a Laravel application on an Ubuntu VM with Nginx. The pro ...

Clicking a button will bring back the component to its assigned ID

How can I dynamically add a component <SaveTask/> to a specific div tag with the id of <div id="saveTask">? When I use this.setState(), it replaces the container and displays only the <SaveTask/> component. However, I want to re ...

Seeking the perfect message to display upon clicking an object with Protractor

Currently, I am using Protractor 5.1.1 along with Chromedriver 2.27. My goal is to make the script wait until the message "Scheduling complete" appears after clicking on the schedule button. Despite trying various codes (including the commented out code), ...

After a refresh, jQuery's mousenter event is not functioning

I am currently working on a fun project called Etch-a-Sketch for The Odin Project, and I have a jquery grid that can be redrawn with the click of a button. Initially, the grid allows the user to choose the size and then draw on it using .mouseenter. Howev ...

Guide on building a Dynamic factory in AngularJS

For my project, I need to implement a dynamic factory in AngularJS with a unique name. Here is an example of what I am trying to achieve: function createDynamicFactory(modId) { return myModule.factory(modId + '-existingService', function ...

Angular 4, Trouble: Unable to resolve parameters for StateObservable: (?)

I've been working on writing unit tests for one of my services but keep encountering an error: "Can't resolve all parameters for StateObservable: (?)". As a result, my test is failing. Can someone please help me identify and fix the issue? Here& ...

Unintended redirects are occurring with AJAX requests when using the send() method

After loading the web page, I utilize AJAX to populate a list asynchronously. However, when the AJAX request is sent to retrieve data for the list box, instead of receiving JSON data as expected, an unintended web page containing the list box is returned. ...

Display a JSON encoded array using Jquery

Within an ajax call, I have a single json encoded array set: $var = json_encode($_SESSION['pictures']); The json encoded array is stored in a variable called "array" When I try to display the contents of "array" using alert, I get this respons ...

Set up a WhatsApp web bot on the Heroku platform

I am currently in the process of developing a WhatsApp bot using the node library whatsapp-web.js. Once I finish writing the script, it appears something like this (I have provided an overview of the original script) - index.js const {Client, LocalAuth, M ...