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(" ");
-
why not write the data into a file?Nina Scholz– Nina Scholz2020年02月24日 14:15:31 +00:00Commented Feb 24, 2020 at 14:15
-
Your desired output seems all over the place... prompt, console, text file..palaѕн– palaѕн2020年02月24日 14:16:51 +00:00Commented Feb 24, 2020 at 14:16
-
You can read from the text file directly. See if this is helpful stackoverflow.com/questions/14446447/…rootkonda– rootkonda2020年02月24日 14:16:52 +00:00Commented Feb 24, 2020 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 .... stackoverflow.com/questions/60365578/…caramba– caramba2020年02月24日 14:19:16 +00:00Commented Feb 24, 2020 at 14:19
-
Can you explain to us how are you reading the file?Calvin Nunes– Calvin Nunes2020年02月24日 16:26:41 +00:00Commented Feb 24, 2020 at 16:26
3 Answers 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)
Comments
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)
1 Comment
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)```