# Initializing a 2D Array with a Ton of Zeroes

## Recommended Posts

Hi! I'm trying to make a 2D array with a ton of zeroes. For some reason, this does not work. (By does not work, I mean I get errors when accessing the array. If I initialize the array manually, it's smooth sailing.)

``````  var blankRow = [];

for(var x = 0; x < world[0].length; x++) {
blankRow.push(0);
}
for(var y = 0; y < world.length; y++) {
processedWorld.push(blankRow);
}``````

It pushes the blank row full of zeroes (the horizontal axis) then pumps that into the destination array (processedWorld, the vertical axis)

What am I screwing up

P.S. "world" is a different array from "processedWorld" and has already been defined, and works perfectly.

##### Share on other sites

Looks like you're pushing the same blankRow into all the rows.  So any change to any row will effect all rows.  Whereas you probably want to push a new bankRow into each row?  Solution: move the x loop into the y loop.

You may also want to consider an alternative data structure to an array if you're doing higher level manipulation.

##### Share on other sites

This worked, thanks!

##### Share on other sites

The most simple way is probably:

``````const DIM = 100
const map = new Array(DIM).fill(0)``````

For the 2D variant you're using:

``````const X_SIZE = 4
const Y_SIZE = 2
const map = new Array(X_SIZE).fill(new Array(Y_SIZE).fill(0))

// Better:
function createArray (length, fill) {
return new Array(length).fill(fill)
}

const map = createArray(X_SIZE, createArray(Y_SIZE, 0))``````

Depending on your coordinate system you might want to invert X and Y.

Note that fill is really naive, I normally use some other helpers that allow a 'fill' function to accept a function which allows a really nice clean API for creating simple or complex arrays.