An easy guide to showing a list of numbers according to a specific condition using javascript

Can someone help me figure out how to generate a list of numbers based on two criteria?

  • The number must be divisible by 3
  • The number must not end with 3

I need to create this list within the first 50 numbers using JavaScript.

Desired Output:

6, 9, 12, 15... 45

My Attempt:

function getNumbers() {
  var result = [];
  for (var i = 1; i <= 50; i++) {
    if (i % 3 == 0 && i % 10 != 3) {
      result.push(i);
    }
  }
  return result.toString();
}

console.log(getNumbers())

Answer №1

This solution appears to be in accordance with the specifications - however, it's worth noting that the specifications indicate it should start at 6 rather than 1.

const numbers = [...Array(50).keys()].
  filter(num => num !== 0 && num%3 === 0 && !String(num).endsWith("3"))

console.log(numbers)

NOTE: If you prefer to skip testing for 0, you can modify [...Array(50).keys()] to [...Array(50).keys()].slice(1)

Answer №2

In order to achieve this, you can implement a conditional check where the modulo of 3 is equal to 0 and the modulo of 10 is not equal to 3. To enhance the code structure, you may integrate this solution with mplungjan's answer; however, I opted to showcase a mathematical approach instead of utilizing the !String(num).endsWith("3") method proposed by mplungjan.

I initiated the iteration at 1 rather than 0 to prevent adding 0 to the array. Additionally, I rectified the return statements for improved clarity.

function getNumbers() {
  var result = [];
  for (var i = 1; i < 50; i++) {
    if (i % 3 === 0 && i % 10 !== 3) {
      result.push(i);
    }
  }
  return result;
}

console.log(getNumbers())

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

Negatives of utilizing two different UI libraries within a single react project?

I have been contemplating a decision that may be considered unconventional from a technical standpoint. Despite my search efforts, I have not come across any explanation regarding the potential drawbacks of this decision. Imagine creating a React website ...

When the mouse is clicked, the character fails to reach the intended destination or moves in the wrong direction on the HTML canvas

UPDATE: RESOLVED I am currently working on a game where the character moves by right-clicking. The character is meant to walk slowly, not teleport, towards the destination set by right-clicking on the canvas. However, I have encountered an issue where the ...

Transferring temporary information from server to controller using angular-file-upload

Currently, I am utilizing the angular-file-upload library which can be found at this link: https://github.com/danialfarid/angular-file-upload. In the example provided on that page, data from a file is sent to the backend from a controller using the availab ...

Adjust the width of a div element using the transform property to rotate it and modify the

Having an issue with a particular style here. There's a div containing the string "Historic" that has a CSS transform rotate applied to it and is positioned in relation to another sibling div. When I change the string to "Historique" for international ...

Testing a function that utilizes an asynchronous function with Jasmine

Explanation on how to validate this function: let self = this; self.someVariable = "default value"; self.test = function() { self.functionWhichReturnsPromise().then(function() { self.someVariable = "updated value"; }); } A test scenario is pro ...

Struggling with overlaying Bootstrap modals on top of each other

This idea is inspired by the topic Multiple modals overlay I am working on developing a folder modal that allows users to either 1) open an existing file or 2) create a new file within each folder modal. To see how it functions, please run the code below ...

How to retrieve an array from a JSON object with JavaScript

After receiving an object from the server, I am specifically looking to extract the array ITEMS. How can I achieve this? I attempted using array['items'] but it did not yield the expected result and returned undefined { "items": [ { ...

Tips for including additional elements in a preexisting array

I'm encountering an issue with the code below: String[] where; where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"); where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"); Currently, these two appends are generating compilation ...

Tips for surviving a server restart while using sequelize with a postgres database and handling migrations

Within my express application, I utilize Sequelize for database management. Below is the bootstrap code that I use: db.sequelize .sync({ force: true}) .complete(function(err) { if (err) { throw err[0]; } else { //seed requi ...

Is picking Slicers in VBA categorized as an Array now that it has evolved into a Data Model?

I need assistance selecting powerpivot slicers with date variables. The slicers represent dates from Monday to Saturday or in the format of 1/19-1/25. I am struggling to figure out how to select the slicers using my date strings for Monday and Saturday, ra ...

Exploring Interpolation Techniques in PyLab

I am working with two arrays named x and y that contain coordinates for a specific function. Here is an example: x=[0,1,2,3,4,5] y=[0,1,5,20,30,32] When I use pylab.plot(x,y), I can visualize the function smoothly. Is there a method to determine the x ...

Utilize conditional styling in Vue using CSS

I am having difficulty implementing a conditional Vue statement to change the CSS style based on the text value. Despite trying other tutorials, I have had no success due to my limited experience with Vue. For example, if I want the class to be "is-succes ...

How can I arrange the ng-class based on the clicked item's order?

http://plnkr.co/edit/pUtuZy?p=preview In this scenario, there are three different border classes available: .border1 { border: 1px solid #66FFFF; } .border2 { border: 1px solid #33CCFF; } .border3 { border: 1px solid #0099FF; } The goal is to as ...

Which symbol is preferable to use in JS imports for Vue.js/Nuxt.js - the @ symbol or the ~ symbol?

I am seeking guidance on a matter that I have not been able to find a clear answer to. Webapck typically uses the ~ symbol as an alias for the root directory. However, I have noticed that some developers use the @ symbol when importing modules using ES6 s ...

What is the best way to ensure that a canvas created using JavaScript spans 100% of the width?

Working with a canvas element generated by Javascript, see the code snippet below: http://jsfiddle.net/mtvzgnmm/ <div id="circle"></div> <script> $('#circle').circleProgress({ value: 0.75, size: 400, ...

What is the process for implementing a creation date for an object in Java?

This assignment requires implementation of the following: I need to create a private Date variable called dateCreated to store the creation time of the object. private Date dateCreated; In addition, I must create a getter method for dateCreated. public ...

PHP Combining two arrays by adding an element to each existing element

How can I merge elements from one array with each element in another array? For instance: $colors = array("black", "white", "yellow"); $numbers = array("1", "2", "3"); I am looking to create a new array that combines them all like so: $colornumber = a ...

Issues with Videojs Responsive Lightbox Functionality

I am looking for a solution to display VideoJS in a lightbox while keeping it responsive. I came across this helpful code snippet: https://github.com/rudkovskyi/videojs_popup. It seemed perfect until I tried using it with the latest version of Videojs and ...

When attempting to import Quill-blot-formatter with react-quill via next/dynamic, the registration process fails and continues to display a loading message

After creating a function component and configuring quill-blot-formatter with react-quill, I added the blotFormatter to the modules list. Then, I imported this module using next/dynamic on the desired page. The custom function looks like this: import Reac ...

Wait for all asynchronous functions in Node.js to finish before proceeding with the remaining code

I am facing an issue in my code where I have 2 for loops executing the same async function, but I need the code to wait until both loops finish executing before proceeding. Here is a snippet of my code: for(var a = 0; a < videoIds.length; a++){ ...