# 2d array with empty elements

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.

• 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 – Big T Larrity Jul 1 '19 at 8:58
• 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? – DMGregory Jul 1 '19 at 14:47
• @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. – kojow7 Jul 1 '19 at 17:36

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]
];

• Thank you, I didn't realize that a single underscore could be used as a variable name. – kojow7 Jul 1 '19 at 19:03
• 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. :) – DMGregory Jul 1 '19 at 19:07
• huh that's interesting – Ocelot Jul 3 '19 at 6:18