Cheatsheet for working with 2D arrays in JavaScript

Arrays are basic data structures present in all programming languages I’ve been worked with so far: JavaScript, Ruby, Python, PHP. It’s easy enough to understand normal arrays but I’ve found that introducing an extra layer (ie. a second dimension) makes it exponentially harder to work with. This cheatsheet is a growing list of tips and tricks for using 2D arrays in JavaScript. The idea is portable to other languages, since the ideas are universal.

Rule #1: Always use a 1D array if you can help it

We can represent a grid, say a tic tac toe board, using a single array:

But I’ve seen people opt for a 2D array instead:

I wonder, why would anyone do that, especially for a small 3×3 grid? I couldn’t come up with a good, sensible answer. Accessing the 2D array is pain compared to the 1D array using iterators:

What about when the array is much larger? Say, 10×10? Let’s also use a for loop to generate them so we don’t have to manually generate the array (because we’re lazy!):

With the 2D array, we’re basically splitting a grid into columns and rows. So if we were to iterate through every single element, we’d have a for loop nested inside another for loop, which means we’ll go row by row, and within each row, we’ll go from column 1 to the last column. To this rhythm…

R1 C1 >> R1 C2 >> R1 C3 >> … >> R1 C10
R2 C1 >> R2 C2 >> R2 C3 >> … >> R2 C10

R10 C1 >> R10 C2 >> R10 C3 >> … >> R10 C10

Now would it make more sense to use a 2D array? Will it provide greater versatility down the road when we want to manipulate the array?

2D array is good for accessing an element based on a specific coordinate

2D arrays would indeed be superior to 1D arrays if we could access an element based on a specific coordinate, like R3 C6. Do they give us that flexibility?

Yes. R3 C6? That’s as simple as calling grid[2][5]! We now have access to the value 26. That was much easier than using a 1D array, which would require us to first do some calculations before being able to pinpoint the value of a specific element that corresponds to the third row fifth column.

What happens if we need to programmatically change values of the elements surrounding a specific element?

I’ll explore this in tomorrow’s update of this article!