Sign in to follow this  
ItsYaBoiWesley

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 this post


Link to post
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 this post


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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.