0

Im importing an txt file into an array using jquery like so:

var testarray= new Array();
    $.get('locationtosavedfile', function(data){
            testarray= new Date(data.split('\n'));
            console.log(testarray);
        });

The contents of the file look like so:

"October 12, 2013 06:06:00"
"October 12, 2013 06:36:00"
"October 12, 2013 07:19:00"
"October 12, 2013 07:24:00"
"October 12, 2013 07:39:00"
"October 12, 2013 07:54:00"
"October 12, 2013 08:06:00"
"October 12, 2013 08:46:00"
"October 12, 2013 09:06:00"

The file is loaded into the array fine though its not making a date due to an formatting issue but im sure it should be okay? the text its importing is the same format as

new Date("October 12, 2013 10:12:00");

Which when added manually does work.

The error im getting is: Invalid Date. If I output the array the results are all there and separated by a comma.If there is something i'm missing let me know..

1 Answer 1

3

You're trying to pass an array of such strings to new Date, not doing them one at a time.

Use ES5 .map to convert an array from one format to another:

testarray = data.split('\n').map(function(v) {
    return new Date(v);
});
Sign up to request clarification or add additional context in comments.

12 Comments

var testarray = new Array(); $.get('myfilehere.txt', function(data) {} testarray = data.split('\n').map(function(v)) { return new Date(v); }); this still does not work for me I have tried a few variations always errors how can I fix/
@MarkCowley define "doesn't work". As it stands, you do know you can't use testarray until after the $.get call is completely finished, don't you? You need to start up anything else that depends on testarray inside the callback.
Yes I know that. Try compile it it wont work. Just formatting issues left right center
Okay I got it to work by changing the curly brackets around although it seems not to assign each item an [i] how to fix?
@MarkCowley you're not giving us much to go on - when I test the above code it works, although you do have to ensure that there's no \n on the final line of data, otherwise the .split will create an empty element on the end of the list.
|

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.