Unable to provide desired array return

Greetings from a newcomer to StackExchange! I recently delved into the world of programming and am currently learning JavaScript. My goal is to create an array of random numbers with 'n' size in order to experiment with sorting and searching algorithms to determine efficiency.

Despite my efforts, I seem to have hit a roadblock. I attempted this task yesterday but still cannot identify the root of the issue - my result is always an empty array.

My current setup involves using inquirer 0.12.0 for user input.

var inquirer = require('inquirer');

// GENERATE AN ARRAY WITH A SIZE OF n CONTAINING RANDOM NUMBERS
var value;
var limit;

var questionRandomSize = [{
  type: 'input',
  name: 'randomsize',
  message: 'Enter the maximum number for randomness.',
  validate: function (limit) {
    if (limit > 0) {
      return true;
    } else {
      return 'Please enter a number to proceed.'
    }
  }
}];

var questionArraySize = [{
  type: 'input',
  name: 'arraysize',
  message: 'Enter the size of the array.',
  validate: function (value) {
    if (value > 0) {
      return true;
    } else {
      return 'Please enter a number to proceed.';
    }
  }
}];

var nArray = new Array();

function generateArray(value) {
  for (i = 0; i < value; i++) {
    nArray.push(generateRandomNumber(limit));
  }
}

inquirer.prompt(questionRandomSize, function (limit) {
  function generateRandomNumber(limit) {
    return Math.floor(Math.random() * limit);
  }
  inquirer.prompt(questionArraySize, function (value) {
    generateArray(value);
    mainMenu();
  });
});

// MAIN MENU FUNCTION
function mainMenu() {
  if (nArray.length === value){
    console.log(nArray);
  } else {
    generateArray(value);
  }
}

Thank you in advance for your assistance!

Answer №1

Your code contains various errors, but I have fixed them and provided a working version below:

var inquirer = require('inquirer');

var questionRandomSize = [{
    type: 'input',
    name: 'randomsize',
    message: 'Enter the maximum random number.',
    validate: function (limit) {
        if (limit > 0) {
            return true;
        } else {
            return 'Please enter a valid number to proceed.'
        }
    }
}];

var questionArraySize = [{
    type: 'input',
    name: 'arraysize',
    message: 'Enter the array size.',
    validate: function (value) {
        if (value > 0) {
            return true;
        } else {
            return 'Please enter a valid number to continue.';
        }
    }
}];

var nArray = [];

function createArray(limit, size) {
    for (var i = 0; i < size; i++) {
        nArray.push(generateRandomNumber(limit));
    }
}

function generateRandomNumber(limit) {
    return Math.floor(Math.random() * limit);
}

inquirer.prompt(questionRandomSize, function (limit) {
    inquirer.prompt(questionArraySize, function (size) {
        createArray(limit.randomsize, size.arraysize);
        displayMenu();
    });
});

//MENU
function displayMenu() {
    console.log('array', nArray);
}

Output example:

? Enter the maximum random number. 2
? Enter the array size. 4
array [ 0, 1, 0, 1 ]

The errors that were corrected include:

  • Misunderstanding the return value from prompt method as user input instead of an object with properties
  • Improper scope placement of the generateRandomNumber function
  • Unnecessary recursive call within createArray function

Additional notes:

  • Use [] when creating arrays instead of new Array()
  • Always declare variables using var, let, or const
  • Consider updating inquirer to the latest version for improved functionality with Promises

Answer №2

Welcome to CodeHelp! If you're looking to create an array of a specific size filled with random numbers within a set limit, you've come to the right place.

The issue at hand doesn't require the use of the inquirer library, so you can eliminate that unnecessary code from your query.

To solve this problem, consider crafting a concise function that generates the desired array for you.

function generateRandomArray(size, limit){

    // Initialize an empty array
    var new_array = [];

    // Perform the following operations 'size' number of times
    for(var i = 0; i < size; i++){

        // Generate a random number between 0 and 'limit'
        // Push it into the array.
        new_array.push(Math.floor(Math.random() * (limit + 1)));

    }

    // Return the final array
    return new_array;

}

This solution only spans across 4 lines. Simply call generateRandomArray(size, limit) to obtain an array of size size containing numbers ranging from 0 to limit:

var size  = 10;
var limit = 100;
var result_array = generateRandomArray(size, limit);

You can obtain values for size and limit through various means such as user input fields or utilizing JavaScript's prompt() method. Best of luck with your coding!

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

Escaping the setTimeout loop

I'm struggling to find a solution for breaking out of a setTimeout loop. for (var i = 0; i < 75; i++) { setTimeout(function (i) { return function () { console.log("turn no. " + i); if (table.game.playerWon) { con ...

Validating usernames using Jquery's remote method检verifying the username

Struggling with the validation plugin and Laravel 4.2. I've been attempting to use ajax to check the username, but it's not functioning as expected. No matter if the username exists or not, it always appears available. Another problem arises whe ...

What might be causing my mongoose query to take so long? (~30 seconds)

I've encountered a problem with a route in my application. This specific route is supposed to fetch an array of offers that a user has created on the app by providing the user's id. Initially, when the user has only a few offers, the query execut ...

React Navbar toggle button malfunctioning with Bootstrap 4.5.3 - troubleshooting needed

My toggle button is not working in my React app. Can someone please help me troubleshoot this issue? Should I use ul li tags or is there a library that can create a responsive navbar for React? import React from "react"; import { Link, NavLink } ...

Error encountered in PHP array foreach loop when outputting MySQL query: "illegal offset" and "invalid argument" exceptions.printStackTrace()"

To simplify this explanation, I've condensed the example code. I understand where the issue lies - I just need help using a foreach loop to display the results of my MySQL query. Here is an example array structure: $thetablestructure = array( array ...

Enhanced dropdown menu with Vue.js

Trying to manage two select lists where their combined values equal a maximum size. For example, if the max number of people is 20 and 5 children are selected, only a maximum of 15 adults can be added, and so on. My latest attempt: Template: <div cla ...

Else statement malfunctioning with Alert() function

I have noticed an issue with my user input field. Even when I enter a valid genre name, the alert prompt still appears saying it is not a valid genre. This occurs after entering both valid and invalid inputs. For example, if the user enters "horror," whic ...

The array cannot be accessed outside of the block

I have a method that generates an array called 'venues'. However, every time I attempt to access this array in a different method, it shows as 'null'. Here is the method: - (void)startSearchWithString:(NSString *)string { [self.las ...

steps to extract routing into its own component

Is it possible to extract this routing logic into a separate component? I attempted to use map but it didn't work I want to have only a single route, and change the 'path' when a specific link is clicked const Home = ({ code }) => { re ...

Retrieving information from an array in Laravel with keys that contain spaces

Currently, I am utilizing the Alpha Vantage API and making an external call. One issue that has arisen is that the response includes numerical values within the string. I'm exploring ways to parse this out using Laravel 5.2. Below are snippets of my c ...

Why are my API routes being triggered during the build process of my NextJS project?

My project includes an API route that fetches data from my DataBase. This particular API route is triggered by a CRON job set up in Vercel. After each build of the project, new data gets added to the database. I suspect this might be due to NextJS pre-exe ...

Transforming an array into JSON format in order to verify the data

After sending an Ajax call to a PHP file, I receive an array in return. My objective is to verify the values of the received data. Take a look at the following Javascript/jQuery code snippet: $.ajax({ url: "file.php", type: "POST", data: {&a ...

Creating SQL statements in PHP programming

I am struggling to take all the values from the post array and incorporate each one into a select statement that updates the preceding value. My issue lies in executing this process in PHP due to difficulties with string escaping. This represents the SQL ...

Using the OR Operator with a different function in React

Struggling with setting the day flexibility using disableDate(1,2,3,4,0) but it's not functioning as expected. Can you assist me in fixing this issue? Here is the function snippet: const disableDate = (date) => { const day = date.day(); retur ...

Can a form be selected and submitted using only its class as a selector?

When trying to select and submit a form using only the class as a selector, I encountered an issue: $("form.class").submit(...) doesn't seem to work... however: $("form#id").submit(...) works perfectly fine. Any idea what could be causing this di ...

Unable to loop through distinct elements

I have encountered a list of errors like so: n.errors.full_messages # => ["Password can't be blank", "Password can't be blank", "Password is too short (minimum is 3 characters)"] My intention is to extract the unique elements from this array ...

Tips for modifying javascript code to have popups appear as bPopup instead of in a separate popup window

Is there a way to modify the following code so that popup windows open as dpopups instead of just in a new popup window ()? $(document).ready(function() { var table = $('#taulu').DataTable( { "ajax": "taulu.php", "columnDefs" ...

Retrieve data from AJAX request using array index

A certain script in my possession is able to extract data from a JSON file and store the name property of each element in an array. HTML <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script> var names = []; var f ...

Arrange an asynchronous function in Node.js

I have been attempting to set up a schedule for an asynchronous function (with async/await return type) to run every two minutes. Although I have tried using the generic setInterval, as well as various node modules such as node-schedule, cron, node-cron, ...

What purpose does this particular express variable serve?

I am currently diving into the world of JavaScript, with a basic programming background to boot. However, I have always stumbled when it comes to grasping OOPs concepts. For instance, we start by importing what I believe is the express module through &apo ...