1
\$\begingroup\$

I am working on a game with a number of different grid components. Each grid would be about 15 squares wide by 15 squares tall. Each of the squares may either contain an item or not.

Is there any way to create this array and only include the components that have a value. Example (for a 5x5 array):

[
   [5,3, , ,3],
   [ ,1,0,2,2],
   [ , , , , ],
   [5, , ,2, ],
   [ , , , ,1]
]

Is there any way to do this in JavaScript or should I just add a bunch of NULL values to the array?

A simplified version of this, might be an Xs and Os game. Before the game starts all squares are empty. Over time, some of the grid may have either Xs or Os in specific squares.

\$\endgroup\$
  • 1
    \$\begingroup\$ adding the null values sounds perfect. I was thinking in your X and O's example you could just have 0 = empty; 1= X, 2 = o or whatever feels right to you \$\endgroup\$ – Big T Larrity Jul 1 at 8:58
  • \$\begingroup\$ Did you try using null values? If it worked, post it as an answer. If you're worried that's the "wrong" way to do it, ask yourself, what do you expect the array to return if you try to read one of those blank entries? \$\endgroup\$ – DMGregory Jul 1 at 14:47
  • \$\begingroup\$ @DMGregory I guess the issue was that I was wanting to look at the array and see it the same way I would see it on the screen so that I could easily see at a glance which areas of the array had something in them or not. I guess it's not a big deal though and I will just use null values. It would have just helped me to visualize things better. \$\endgroup\$ – kojow7 Jul 1 at 17:36
1
\$\begingroup\$

If you want the map to appear as close as possible to what you've written above, without a lot of nulls to type out and clutter reading, you could define a helper variable first:

var _ = null;

var tileMap = [
  [5,3,_,_,3],
  [_,1,0,2,2],
  [_,_,_,_,_],
  [5,_,_,2,_],
  [_,_,_,_,1]
];
\$\endgroup\$
  • \$\begingroup\$ Thank you, I didn't realize that a single underscore could be used as a variable name. \$\endgroup\$ – kojow7 Jul 1 at 19:03
  • 1
    \$\begingroup\$ I don't recommend it as a general practice, but for a special case like this, if it helps you read and edit your code to get the behaviour you want, it could be worthwhile. :) \$\endgroup\$ – DMGregory Jul 1 at 19:07
  • \$\begingroup\$ huh that's interesting \$\endgroup\$ – Ocelot Jul 3 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.