2

I'm trying to take an input from a text file (for example 3 7 9 53 2) and place those values into an array.

3 7 9 53 2

I tried with prompt(), but I obviously can only add them one by one:

for (var i = 0; i < n; i++) {
    Array[i] = parseInt(prompt("Value for Array"));
}

However, I want to read line by line and add them to an array. A line will contain hundreds of numbers. is there a way to fill an array quickly by copying and pasting the data into the console? Like in java

String[] line = sc.nextLine().split(" ");
Mahatmasamatman
  • 1,537
  • 2
  • 6
  • 20
Novaen.
  • 21
  • 2
  • why not write the data into a file? – Nina Scholz Feb 24 '20 at 14:15
  • Your desired output seems all over the place... prompt, console, text file.. – palaѕн Feb 24 '20 at 14:16
  • You can read from the text file directly. See if this is helpful https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file – rootkonda Feb 24 '20 at 14:16
  • This might help, prompt() is also used there and the string is split by comma which you could change to a space .... https://stackoverflow.com/questions/60365578/pushing-new-comma-separated-string-of-numbers-to-an-existing-array/60365636#60365636 – caramba Feb 24 '20 at 14:19
  • Can you explain to us how are you reading the file? – Calvin Nunes Feb 24 '20 at 16:26

3 Answers3

3

First use the split function to transform your string into array, then for each element of your array convert it into a number, Then you are done :)

var c = "12 2 23 3 4"
var res = c.split(" ")
for (var i=0; i < res.length; i++) {
  res[i] = parseInt(res[i])
}
console.log(res)
Omar Aldakar
  • 505
  • 2
  • 8
2

Assume let result=[], so you want to add string in an array which can be directly assigned as "result=c.split(" ")" in case result is empty but if you want to assign multiple strings to the same array you can refer code.

var c = "12 2 23 3 4"
let d=" 1 2 3 4 5 6"
if(result.length === 0){
  result = c.split(" ")
}else{
 let tempArray = d.split(" ")
result.push(...tempArray)
}
console.log(result)```

Pallavi
  • 21
  • 7
2

You can do it with an inliner .split(" ") and .map(Number)

The first one will split the string by spaces, creating an array of each word/number, the second one will loop this array and convert every word to number, see below

let data = "3 7 9 53 2"
let array = data.split(" ").map(Number)

console.log(array)
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48