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(" ");
5
  • why not write the data into a file? Commented Feb 24, 2020 at 14:15
  • Your desired output seems all over the place... prompt, console, text file.. Commented Feb 24, 2020 at 14:16
  • You can read from the text file directly. See if this is helpful stackoverflow.com/questions/14446447/… Commented 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/… Commented Feb 24, 2020 at 14:19
  • Can you explain to us how are you reading the file? Commented Feb 24, 2020 at 16:26

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

functionnal programming is very nice
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)```

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.