dorien
dorien

Reputation: 5397

Load 2d array from file in javascript

I have an array as follows in javascript:

var linePoints = [[0, 3], [4, 8], [8, 5], [12, 13]];

But I would like to load this from a textfile instead of defining it in the code. The file:

input.txt:

0 3
4 8
8 5
12 13

I noticed this other post, which talks about something similar, but for a 1D array. I was wondering if there is a special function to do this for 2D. In java, I would read each line, then split it. But to be fair, I am new with javascript.

Upvotes: 1

Views: 2601

Answers (3)

trincot
trincot

Reputation: 350252

You need to pay attention to different newline styles, and you probably want the array to have numbers, not strings.

So I propose this code:

$.get("textFile.txt", function(data) {
    var items = data.split(/\r?\n/).map( pair => pair.split(/\s+/).map(Number) );
});

Upvotes: 2

Michele Ricciardi
Michele Ricciardi

Reputation: 2117

This should do what you're looking for:

$.get("textFile.txt", function(data) {
      var items = data.split("\r\n").map(function(el){ return el.split(" ");});
  });

Here a working example: http://plnkr.co/edit/htsf9yBuygAhv7vznS2g?p=preview

Upvotes: 4

jered
jered

Reputation: 11571

There's no built-in generalized function for parsing input the way you want. However you could take advantage of the String.split() function which will break a string into any number of smaller strings based on the delineator you pass it:

var foo = "0 3";
var bar = foo.split(" "); // split based on single space character
console.log(bar); // ["0", "3"]

Upvotes: 0

Related Questions