3

I'm trying to create a 2D array with javascript that I can ultimately put inside a nested loop to extract X/Y information.

What am I doing wrong here?


function createMatrix(){
    let colcount = 0;
    let rowcount = 0;

    var pixel_array = new Array();
    var y_array = new Array();

    for (var i = 0; i <= 100; i++){
        var checker = (i+1) % 10;
        if(checker == 0){
            y_array.push(i);
            //create new X array
            pixel_array[rowcount] = [];
            //push column data into row array
            pixel_array[rowcount].push(y_array);
            //create new Y array 
            var y_array = new Array();
            //increment row counter
            //reset column counter
            parseInt(rowcount++);
            colcount = 0;
        }else{
            y_array.push(i);
            parseInt(colcount++);
        }
    }

    //sanity check: spit out the matrix
    for (var x=0; x<10;x++){
        for(var y=0; y<10; y++){
            console.log(pixel_array[x][y]);
        }
    }

}

I was expecting to call a specific X/Y 'coordinate' and extract the information from that 'cell'. However, I'm getting an error that basically says the [Y] part of the array is not defined.

Looking at console.log and console.table - I can see the X array is filled, but it isn't like I'd expect, just a list of numbers not another array.

Edit: To be more specific, my goal is to create a 2D array from a single For loop. The nested for loop at the bottom of the code is shown as an example of how I would like to call the 'cells' [X][Y].

1 Answer 1

3

This code:

pixel_array[rowcount] = [];
//push column data into row array
pixel_array[rowcount].push(y_array);

creates a new array, stores it in pixel_array[rowcount], and then pushes y_array into it. So at that point, you have an array (pixel_array) with an entry that's an array (the one you created via []), with an entry that's an array (y_array). That's closer to a 3D array than a 2D array.

You may be overcomplicating it a bit. I can't quite make out what you want your final array to be, so here's an example of creating a 3x4 "2D array" (it isn't really¹, it's an array of arrays, but...) with the numbers 1-12 in it, see comments:

// Create the outer array
var array = [];
for (var x = 0; x < 4; ++x) {
    // Create the inner array for this row and store it in `array[x]`
    var inner = array[x] = [];
    for (var y = 0; y < 3; ++y) {
        // Set the value of the inner array at `y`,
        // which is also `array[x][y]`
        inner[y] = (x * 3) + y + 1;
    }
}
console.log(array);
.as-console-wrapper {
    max-height: 100% !important;
}


In a comment you've said:

I want to create a 2D array from a single For loop. So in my example I'm looping 0-99, with the expected result being a 10x10 'matrix' (0-9, 10-19, 20-29, etc).

Here's an example doing that:

// Create the outer array
var array = [];
var inner;
for (var n = 0; n < 100; ++n) {
    // Time to create a new inner array?
    if (n % 10 === 0) { // It's important that this condition is true on the first loop iteration
        inner = [];
        array.push(inner);
    }
    // Add this `n` to the current inner array
    inner.push(n);
}
console.log(array);
.as-console-wrapper {
    max-height: 100% !important;
}


¹ "it isn't really, it's an array of arrays" - JavaScript doesn't have multi-dimensional arrays. It has arrays that can contain other arrays. For many purposes, the distinction doesn't really matter, but it means (amongst other things) that the arrays can be jagged: Not all entries in the outer array have to have the same length. (In fact, they don't even have to be arrays.)

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

4 Comments

Thanks for the reply T.J. - I now relize I should have been more specific in my question: I want to create a 2D array from a single For loop. So in my example I'm looping 0-99, with the expected result being a 10x10 'matrix' (0-9, 10-19, 20-29, etc). Ultimately I will use this with a Nth For loop to create an NxN matrix.
@edwardrford - Ah, that's simpler than what I was doing. :-) I've added an example to the answer.
(insert face palm emoji) - Wow, I was thinking waaaay too hard about that one. Thanks T.J. - I really appreciate the answer.
@edwardrford - LOL, we've all done it. Happy coding!

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.