Jump to content

Initializing a 2D Array with a Ton of Zeroes


ItsYaBoiWesley
 Share

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.

Link to comment
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.

Link to comment
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.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...