-1

I have file called "temperatures.txt". It includes the text:

22,
21,
23

How do I copy the file's content into a JavaScript array?

var temperatures = [22, 21, 23];
6
  • 2
    Read file content, split it's content on \r\n and you have JS array. Commented Feb 1, 2017 at 14:39
  • 3
    Possible duplicate of Reading .txt file into array Javascript/jQuery Commented Feb 1, 2017 at 14:39
  • @Justinas - really? Commas should be part of the array? Commented Feb 1, 2017 at 14:39
  • @HappyJoe - are the commas actually a part of the file? And is the file actually split onto new lines as you've shown? Commented Feb 1, 2017 at 14:40
  • @HappyJoe - which part of the problem do you have? Do you know how to read the file? What have you tried so far? Commented Feb 1, 2017 at 14:42

3 Answers 3

1

If your text looks like this

var txt = "22,21,23";

you can convert it to an array like this

var array = txt.split(',');

or, if theres also a new line do

var array = txt.split(',\n');
Sign up to request clarification or add additional context in comments.

Comments

0

Your text

var mytxt = "10,20,30";

Convert into array

var array = mytxt .split(',');

Comments

0

var str = "22,\
           21,\
           23";

// this will remove spaces as well
var result = str.split(/\s*,\s*/);

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.