skip to Main Content

I cannot figure out how to store multiple integers in an array from one prompt
like

const prompt = require('prompt-sync')();
num_array = []
num_array.push(prompt("Enter x amount of integers: "));
console.log(num_array)

in the console, it asks:
Enter x amount of integers:
so i enter: 7 6 5 9 21 4 6 99 820
when the console logs the array, instead of it showing: ‘7 6 5 9 21 4 6 99 820’
I wanna know if it’s possible for it to show: ‘7’, ‘6’, ‘5’, ‘9’, ’21’, ‘4’, ‘6’, ’99’, ‘820’

4

Answers


  1. Chosen as BEST ANSWER

    Someone solved it and their solution wasn't too confusing for me.
    My code:

    const prompt = require('prompt-sync')();
    num_array = []
    num_array.push(prompt("Enter x amount of integers: "));
    console.log(num_array)
    

    My code after their comment:

    const prompt = require('prompt-sync')();
    num_array = []
    num_array.push(prompt("Enter x amount of integers: ").split(" "));
    console.log(num_array)
    

    I tried it and It works
    the person who solved it is @HenryWoody


  2. You could use the split() function to split the input string based on a space, or comma, your choice. And then you could use parseInt() to convert the substrings into integers.

    Try this:

    const prompt = require('prompt-sync')();
    let input = prompt("Enter x amount of integers: ");
    let num_array = input.split(' ').map(num => parseInt(num));
    console.log(num_array);
    
    Login or Signup to reply.
  3. prompt-sync does not automatically split the input string into an array of numbers. We have to do it manually. Something like:

    const prompt = require('prompt-sync')();
    let num_array = [];
    
    let input = prompt("Enter x amount of integers: ");
    let input_array = input.split(' ');
    
    input_array.forEach(item => {
      num_array.push(Number(item));
    });
    
    console.log(num_array);
    
    
    Login or Signup to reply.
  4. Try to split the input into individual integers:

    const prompt = require('prompt-sync')();
    const num_array_input = prompt("Enter x amount of integers: ");
    const num_array_output = num_array_input.split(' ').map(Number);
    console.log(num_array_output);
    
    const num_array_input = "1 2 3 4 5 6";
    const num_array_output = num_array_input.split(' ').map(Number);
    console.log(num_array_output);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search