Generate an array filled with random numbers in JavaScript based on specified criteria

Is it possible to fill an array with a specific number of elements, determined by a given function parameter? The task is to populate myArray with 5 numbers within the range of 5 and 15.

function populateArray(num, startValue, endValue){
var j,
    localArray=[];
for(j=startValue;j<=endValue;j+=1){
    var k = Math.floor(Math.random()* j);
    localArray.push(k);
}
console.log(localArray);
}

The 'num' parameter specifies the number of elements desired in the array – any ideas on how to achieve this? Your help is greatly appreciated!

Answer №1

Click here for the live demo

function fillArray(length, minVal, maxVal){
    var index,
        newArray=[];
    for(index=0; index <= length; index++){
        var randomNum = generateRandomNumber(minVal, maxVal);
        newArray.push(randomNum);
    }
    return newArray; 
}

//Reference: http://stackoverflow.com/a/7228322/402706
function generateRandomNumber(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

console.log(fillArray(10, 8, 12));

Answer №2

for(counter=0;counter<=number;counter+=1){
    var randomValue = Math.floor(Math.random()* (maxValue-minValue) + minValue);
    arrayOfValues.push(randomValue);
}

Answer №3

You're approaching it from the wrong direction:

The for loop should be based on the quantity of numbers required, as shown in this pseudo code:

For j while j < num increase by 1

Your method of generating a random number is also incorrect. The Math.random() function produces a number between 0 and 1. To calculate the space between two numbers, you can use Math.abs(endValue - startValue). Although the absolute value may not always be necessary, it serves as a safeguard against mixing up the numbers. Follow these steps:

Multiply the random value by the space, add the startValue as an offset, then utilize the floor function to eliminate decimals.

Answer №4

Here is a potential solution:

function generateRandomArray(size, minVal, maxVal) {
  // Ensure that minVal is less than or equal to maxVal
  // Ensure that size is greater than or equal to 0

  var array = [];
  var range = maxVal - minVal + 1;

  while (size--) {
    array.push(minVal + Math.floor(Math.random() * range));
  }

  return array;
}

// Here's how you can use this function:
var randomNumbers = generateRandomArray(5, 5, 15);

In the current implementation, you mistakenly used starting and ending numbers of a range to determine the size of the resulting array within the for loop.

I would like to mention two things here. First, if you need to iterate an exact number of times, consider using a while (n--) loop instead of a for loop. I find it helpful for cases where you need to loop N times.

Secondly, when working with ranges, there is often confusion about whether the end value should be inclusive or exclusive. Using prefixes like min and max can clarify this aspect.

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

Struggling to save the resolved data from a promise in Node.js to a variable

I am currently utilizing nodejs to develop REST APIs and I am facing an issue with storing resolved data from multiple promises into a single variable. Here is a snippet of the code I am working with: var resultset={}; function getAllTeams() { retu ...

What should the formatting of a web3py ABI be for an ethereum contract that produces array outputs?

I need to reverse engineer the ABI of an unknown function in an ethereum contract. Here is the raw output split into 256-bit chunks: '0000000000000000000000000000000000000000000000000000000000000060' # unknown '00000000000000000000000000000 ...

Creating a protected pathway using postMessage within an IFRAME for secure communication

Below is an overview of our application. The user interface is sourced from a secure domain , and scripts are hosted on the same domain. The application loads content from the client site within an IFRAME. Due to concerns about trustworthiness, as the co ...

Struggling to implement Datatables row grouping using ajax is proving to be quite challenging

Is there a way to group rows in a table based on date ranges, using the data from the first column ("Due_Date"), and leveraging the rowGroup extension provided by Datatables? I've tried various solutions found online, such as using the data property ( ...

Store various dropdown selections in an array

Questions are being generated from a database for users to answer using a drop-down menu. Upon selecting a specific option, a suggestion is added to an array triggering a JavaScript on-change event. Once all questions are answered, the array including all ...

What is the reason for needing to multiply all the numbers by ten in order to solve this floating point addition problem?

When dealing with floating point arithmetic in Javascript, it's common to see results like 0.2 + 0.1 = 0.30000000000000004, which can be confusing. However, a simple workaround is to multiply the numbers by 10, perform the operation, and then divide b ...

Struct containing an array of unspecified size

During the program execution #include<stdio.h> struct t { char a[5]; char b[]; } temp; int main(){ temp.b[0] = 'c'; temp.b[1] = 'b'; temp.b[2] = '\0'; prin ...

Slate Map by Google Navigation

I have a situation here that is similar to the grey maps, except all the buttons are visible. Everything appears normal except for the Map tiles, which are all grey! It's strange because it loads nicely at zoom level 8 and then zooms in to the maximum ...

The Stack Adding Machine just sits there without adding anything, stuck in limbo until it receives more arguments

After creating a Stack and a Machine to evaluate expressions in Java, I encountered an issue when trying to run the program from the command line. When inputting something like ( 9 + 5 ), the program would just freeze without evaluating the expression. It ...

Is there a way to share another person's contact card using whatsapp-web.js?

Is it possible to send a contact card of someone else using whatsapp-web.js, even if the person is not saved in my phone's contact list? I want to send a contact card to someone who is on my phone's contacts, but the contact information I want to ...

Creating a dynamic form where input fields and their values update based on user input in jQuery

In my form, I have an input field where users will enter an ISBN number. Based on the input number, I need to populate two other input fields: one for book title and one for author name. I am currently calling a JavaScript function on the onblur event of ...

AmplifyJS is throwing an error: TypeError - It seems like the property 'state' is undefined and cannot be read

I am currently working on integrating the steps outlined in the Amplify walkthrough with an Angular cli application. My app is a brand new Angular cli project following the mentioned guide. My objective is to utilize the standalone auth components a ...

Iterating through the array and examining each object

I have a specific structure that I'm working with. In React, I am trying to extract the Internal value from this data. My idea is to create an array of values such as ['Bitcoin', 'Etherium'...] and then map through it. Can someone ...

Utilize AJAX in JavaScript file

I am encountering an issue with the following code: function inicioConsultar(){ $(function(){ $('#serviciosU').change(function(){ if ($('#serviciosU').val()!= "-1") { $.ajax({ url: "@Url. ...

Utilizing a plugin to execute a function in Wordpress

I'm currently facing the challenge of combining two WordPress plugins without the need to modify one to fit into the other seamlessly. My main question is: How can I call a function from one plugin that exists outside of another plugin? For example, ...

AngularJS: Issue with ngChange not being triggered from directive

A Summary of the Issue at Hand I've created a directive that dynamically displays a list of checkboxes. The directive has a parameter named options, which should be an array structured like this in order for the checkboxes to display correctly: var ...

"if the condition is not met, the outcome will not be shown in the while

I have a looping structure that includes conditions for if, else if, and else. However, I have noticed that the else condition at the end of the loop is not being executed as expected. I am currently investigating why this might be happening. Here is the ...

I could really use some assistance right now. I'm in the midst of a project where I'm pulling data from web services in JSON format

Dealing with JSON values in a toast messagein my project involves receiving data from the server side, which includes an array with nested arrays in the response. The image shows the "Secondary_number" array with some values that I need to extract and prin ...

Slider Image Fails to Align Properly

I am struggling to align my image slider in the center of my page. It seems like a simple problem to fix, but I can't seem to get it perfectly centered both horizontally and vertically. Any tips on how to achieve this? The CSS code for the image slide ...

the draggable element turns into nothing

I have created a task manager based on a tutorial I found online. After following the tutorial, I decided to add more functionality by allowing users to add tasks when clicking on a button. Everything works fine until I try to drag one of the added element ...