// A multi-dimensional array (AKA a Matrix, Agent Lionel) // The top-level array is the the rows, each row is made up of columns grid = [[" "," "] [" "," "]];
// A multi-dimensional object // Key of the top level object is the "y", // Keys of the sub-object are the "x", // Values of the sub-object are the value of the coordinate grid = { 0: { 0: " ", 1: " " }, 1: { 0: " ", 1: " " } };
// An array of objects representing a coordinate grid = [{ "x": 0, "y": 0, "value": " " }, { "x": 0, "y": 1, "value": " " }, { "x": 1, "y": 0, "value": " " }, { "x": 1, "y": 1, "value": " " }]
Each of these are different representations of the same bit of data; a
2x2 grid with values of " ". Each have different pros and cons.
The multi-dimensional array is easy to iterate over but it represents
the entire grid. Try using a multi-dimensional grid and setting a
value outside of its bounds:
grid = [] grid[5] = [] grid[5][5] = 'X' console.log(grid) console.log(grid[3]) grid[3][3] = 'X' // uh oh spaghetti-os! console.log(grid)
Notice how the array expands with undefined values to take the place
of any missing sections? That's something you'll need to write a
helper function to deal with.
The multi-dimensional object is not ordered; but you can store only
the rows/columns that matter:
grid = {} grid[5] = {} grid[5][5] = "X" console.log(grid); console.log(grid[3]) grid[3][5] = "X"; // uh oh spaghetti-os console.log(grid);
An object is a pure key-value pair. It makes no assumptions about how
long it is and doesn't expand if you put something in it at position
5. Referencing something at position 3 would still result in
undefined; so we'd need to write helpers for writing/reading from the
grid still.
The array of objects is the most flexible, but hardest to manipulate.
Arrays or pure objects with coordinates as keys means you can be
confident a value will exist at only a single coordinate; however if
you have an array of objects you'd need to inspect each object on
insert to ensure no duplicates.
There's also the option to use the keys of the object to represent
both the x and y coordinate:
grid = {} grid["3,5"] = "X" console.log(grid); grid["4,5"] = "X"
However this may require you to do some work to translate the keys
into coordinates when you want to use them.