Explain Codes LogoExplain Codes Logo

How can I create a two-dimensional array in JavaScript?

javascript
2d-arrays
javascript-arrays
array-creation
Anton ShumikhinbyAnton Shumikhin·Nov 5, 2024
TLDR
const twoDArray = [...Array(5)].map(_ => Array(4).fill(0));

Above yields a minimalist 5x4 grid, every cell initialized with 0. Modify numbers of rows, size of columns, or fill value as required.

Fundamentals of 2D arrays in JavaScript

Dive deeper to comprehend nested arrays and harness them effectively.

Creation: Undefined and defined values

In scenarios devoid of explicit initialization, fill() might be overkill:

let arr = Array.from(Array(rows), () => new Array(columns)); // I solemnly swear I'm up to no good (creating an array!)

The trap of reference issues

A common pitfall with nested arrays is when every row unwittingly references the same array:

// createInceptionArray() - each sub-array dreams it's unique but they aren't! let faultyArray = Array(3).fill(Array(3).fill(0)); // createNonInceptionArray() - where each sub-array is truly unique: let correctArray = Array.from(Array(3), () => Array(3).fill(0));

Access and manipulation of elements

Use double indexing (i.e., array[row][column]), not the deceptive comma separated array[row, column].

Dynamic-sized arrays? No worries!

JavaScript arrays can dynamically resize because they've been practicing yoga:

twoDArray.push(Array(4).fill('new row')); twoDArray[0].push('new column'); // adding a new row or column to your matrix is just a push() away!

Function for 2D array construction

Why not create a reusable function to generate 2D arrays?

function createArray(length, width, initialValue = null) { return Array.from({ length }, () => Array.from({ length: width }, () => initialValue)); } // Here's your one-stop shop to create 2D arrays!

Interaction with 2D arrays like a Pro

Nested iteration using for loops

Looping over a 2D array typically calls nested for loops into action:

for (let i = 0; i < twoDArray.length; i++) { for (let j = 0; j < twoDArray[i].length; j++) { // Perform your magic here! // For access: twoDArray[i][j]; For assignment, just = it. } }

The flatten charm

Use .flat() to un-nest, gracefully transforming to a 1D array:

let flatArray = twoDArray.flat(); // Yeah! Hulk smash(ed) 2D array into 1D!

The art of pretty printing

twoDArray.forEach(row => console.log(`[${row.join(', ')}]`)); // You wouldn't print Mona Lisa in ASCII, so why print array in gibberish?

Philosophies for 2D array wizards

For the power users, here are some advanced techniques to navigate the world of 2D arrays like a pro.

Unequal length sub-arrays

JavaScript, the benevolent dictator of programming languages, welcomes nested arrays of varying lengths:

let unevenArray = [ [1, 2], [1, 2, 3, 4], [1] ];

Memory trade-offs

When dealing with exponentially large data like Google's servers, think memory optimization. Pre-initializing bulky arrays might not be Grandma's secret recipe!

Implications in TypeScript

In TypeScript, you might want to define types for 2D arrays:

let typedTwoDArray: number[][] = [[1, 2], [3, 4]];

Where can I use 2D arrays?

JavaScript's 2D-avatar finds use in applications like game boards, spreadsheet emulation, and matrix computations. Google Sheets, anyone?