Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 142100

2D Javascript Arrays Not Returning Correct Length of "Second Dimension Arrays"

$
0
0

I'm trying to dynamically create a "2D" array in Javascript, but it's more of an array of arrays, obviously. Each array in the array (which I will here on call a "second dimension array") is dynamically allocated based on a file the user uploads. The file is formatted:

Integer representing the number of lines in the drawing the file represents.

Integer representing the number of coordinates which make up a line of that drawing.

The coordinates in that line, each pair separated by a newline.

Another integer representing the number of coordinates in the next line in the drawing.

The coordinates in that line, each pair separated by a newline.

...etc.

For example:

3

3

5.0 2.0

3.4 6.7

7.8 9.6

6

5.0 2.0

3.4 6.7

7.8 9.6

8.9 7.8

9.6 4.3

3.7 2.7

4

4.0 4.0

7.8 5.0

3.8 8.3

2.1 7.6

You get the idea.

Here's my code to parse the file after it has been converted to a string:

function parseDat(contents) {
    var dirtyArray = contents.split("\n");
    var fileArray = dirtyArray.filter(function (n) { return (n !== undefined && n !== null && n !== ""); });


        var lineArray = new Array(parseInt(fileArray[i], 10) + 1);
        lineArray[0] = fileArray[i];

        i++;

        for(var j = 1; j < lineArray.length; j++) {
            lineArray[j] = new Array(fileArray[i]);
            console.log(fileArray[i]);
            console.log("2d array length = " + lineArray[j].length);
            i++;
            for(var k = 0; k < lineArray[j].length; k++, i++) {
                lineArray[j][k] = fileArray[i];
            }

        }

        return lineArray;


}

Basically, I check to see the length the second dimension array should be, which in the example file thing I gave should be 3 for the first line. console.log(fileArray[i]) returns the correct number, but when I use lineArray[j].length, for some reason, the answer is always 1. I've checked lots of other sources for 2D arrays in Javascript and this method of checking the second dimension array's length always works for them.

Please help, I know it's probably just some dumb mistake I'm making.


Viewing all articles
Browse latest Browse all 142100

Trending Articles