javascript 2d array

A javascript 2d array is an array of arrays. Picture a spreadsheet. Each inner array is a row, and each value in that row is a cell. JavaScript has no separate matrix type. Indexes start at 0, so grid[1][2] is the third cell of the second row.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const cell = grid[1][2];

grid has three row arrays. grid[1] is [4, 5, 6]. grid[1][2] reads index 2 of that row, so cell is 6.

The same shape holds a game board, a table of numbers, a grid of pixel values, or the edges of a graph. The rows do not have to be the same length.

Creating a 2D array

Array literal

The literal above is the direct way to write a small fixed grid. You type each row in order. It fits configuration and any other data whose size you already know.

Nested loops

When the size comes from variables, the outer loop builds each row and the inner loop writes each cell. This grid has 2 rows and 3 columns, and every cell is 0.

const rows = 2;
const cols = 3;
const zeros = [];
for (let r = 0; r < rows; r++) {
  zeros[r] = [];
  for (let c = 0; c < cols; c++) {
    zeros[r][c] = 0;
  }
}

The outer loop runs with r equal to 0, then 1. Each pass stores a new array at zeros[r]. The inner loop sets zeros[r][0], zeros[r][1], and zeros[r][2] to 0. zeros is [[0, 0, 0], [0, 0, 0]]. zeros[0] === zeros[1] is false, because each pass of the outer loop created its own array.

Array.from

Array.from can build the same grid in one expression. The object { length: rows } is array-like. The mapping function runs once per index, including indexes that were never set, and its return value becomes that row.

const rows = 2;
const cols = 3;
const zeros = Array.from({ length: rows }, () => Array(cols).fill(0));

Array.from calls the arrow function twice. Each call returns a new array of three zeros. zeros is [[0, 0, 0], [0, 0, 0]], and the two rows are different arrays.

The mapping function also receives the row index, so a cell can depend on its position.

const rows = 2;
const cols = 3;
const numbered = Array.from({ length: rows }, (_, r) =>
  Array.from({ length: cols }, (_, c) => r * cols + c)
);

For row 0 the inner function returns 0, 1, and 2. For row 1 it returns 3, 4, and 5. numbered is [[0, 1, 2], [3, 4, 5]].

The Array.fill pitfall

fill writes one value into a range of indexes. If that value is an object, every slot stores that same object.

const bad = new Array(3).fill([]);
bad[0].push(1);

new Array(3) has length 3 and no elements in it. fill([]) stores one array in all three slots. bad[0] === bad[1] is true. bad[0].push(1) changes that one array, so bad is [[1], [1], [1]].

map does not repair this on its own. map skips empty slots. new Array(3).map(() => []) never calls the function, and index 0 is still empty. fill writes a real element first, and then map runs once per slot. Filling with the number 0 is safe, because each cell stores the number itself, not a shared object.

const good = new Array(3).fill(null).map(() => new Array(4).fill(0));
good[0][0] = 7;

fill(null) makes [null, null, null]. map replaces each null with a new four-element array of zeros. good[0][0] becomes 7. good[1][0] stays 0. good[0] === good[1] is false.

Jagged arrays

A row can be shorter than the row above it. Nothing in the language checks that the lengths match. This triangle gives row i exactly i + 1 numbers.

const triangle = Array.from({ length: 4 }, (_, i) =>
  Array.from({ length: i + 1 }, (_, j) => j)
);

triangle is [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]. triangle.length is 4. triangle[2].length is 3.

Reading and writing a cell

Both indexes are zero-based. An index past the end of an existing row reads as undefined. A missing row is different. The first lookup returns undefined, and the second lookup then throws.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const missingColumn = grid[0][99];
const missingRow = grid[3]?.[0];
grid[1][2] = 60;

missingColumn is undefined. grid[3] is undefined, so grid[3][0] throws a TypeError. In Node the message is Cannot read properties of undefined (reading '0'). The ?. before [0] stops when the row is null or undefined, so missingRow is undefined. The last line writes 60 into the existing row. grid[1] is then [4, 5, 60].

grid.length is the number of rows. grid[r].length is the number of cells in that row. On a jagged array, read the length from the row you are about to walk. grid[0].length is only the width of the first row.

Looping over a 2D array

A pair of for loops gives you the row index and the column index. The inner bound is that row’s length, so a short row does not read past its end.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const cells = [];
for (let r = 0; r < grid.length; r++) {
  for (let c = 0; c < grid[r].length; c++) {
    cells.push(grid[r][c]);
  }
}

r goes from 0 through 2. For each r, c goes from 0 through grid[r].length - 1. cells is [1, 2, 3, 4, 5, 6, 7, 8, 9]. A break in the inner loop stops that loop only. A break in the outer loop stops the walk.

for...of walks the values. The outer loop receives each row array. The inner loop receives each cell. You can break out of either loop. Reassigning the loop variable does not write back into the array.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const cells = [];
for (const row of grid) {
  for (const cell of row) {
    cells.push(cell);
  }
}

The first row is [1, 2, 3], and its cells are pushed in order. The same thing happens for [4, 5, 6] and [7, 8, 9]. cells is [1, 2, 3, 4, 5, 6, 7, 8, 9].

forEach passes the value and the index. It does not give you break. The only way out of forEach, other than finishing the array, is to throw.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const cells = [];
grid.forEach((row, r) => {
  row.forEach((cell, c) => {
    cells.push([r, c, cell]);
  });
});

The outer callback runs for rows 0, 1, and 2. The inner callback runs for each cell of that row. The first three entries in cells are [0, 0, 1], [0, 1, 2], and [0, 2, 3]. The last entry is [2, 2, 9].

map and flat

map builds a new array from the values its function returns. It leaves the array you called it on alone. Mapping each row, and mapping each cell inside that row, returns a new grid.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const doubled = grid.map((row) => row.map((cell) => cell * 2));

doubled is [[2, 4, 6], [8, 10, 12], [14, 16, 18]]. grid is still [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

flat concatenates nested arrays into a new array, down to the depth you pass. The default depth is 1, which is one level of rows.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const flat = grid.flat();
let sum = 0;
for (const cell of flat) {
  sum += cell;
}

flat is [1, 2, 3, 4, 5, 6, 7, 8, 9]. The loop adds those numbers, so sum is 45. grid is unchanged.

flatMap is map followed by flat(1). The callback’s arrays are concatenated into one array.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const plusOne = grid.flatMap((row) => row.map((cell) => cell + 1));

Each row becomes a three-element array of incremented numbers, and flatMap joins those arrays. plusOne is [2, 3, 4, 5, 6, 7, 8, 9, 10].

Find a value

A nested loop can return the row and column of the first match. === is the comparison, so this finds the value itself, not a string that looks like it.

function findCell(matrix, value) {
  for (let r = 0; r < matrix.length; r++) {
    for (let c = 0; c < matrix[r].length; c++) {
      if (matrix[r][c] === value) {
        return [r, c];
      }
    }
  }
  return null;
}

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const found = findCell(grid, 6);
const missing = findCell(grid, 42);

The inner loop sees 6 when r is 1 and c is 2, and the function returns there. found is [1, 2]. Nothing equals 42, so missing is null. If a row is sorted, a binary search of that row can replace the inner scan.

flat().indexOf(value) answers a different question. It returns the index in the flattened array, or -1 when the value is absent. indexOf uses strict equality. When every row has the same length, you can turn that flat index back into a row and a column. Different row lengths make index % width the wrong column.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const width = grid[0].length;
const flatIndex = grid.flat().indexOf(6);
const row = Math.floor(flatIndex / width);
const col = flatIndex % width;

flatIndex is 5. width is 3. row is 1 and col is 2.

Transpose a matrix

Transposing swaps rows and columns. The value at matrix[r][c] moves to result[c][r]. The result has one row per original column. This function assumes a rectangular matrix with at least one row.

function transpose(matrix) {
  const cols = matrix[0].length;
  return Array.from({ length: cols }, (_, c) => matrix.map((row) => row[c]));
}

const grid = [
  [1, 2, 3],
  [4, 5, 6],
];
const turned = transpose(grid);

cols is 3. Column 0 of grid is 1 then 4, column 1 is 2 then 5, and column 2 is 3 then 6. turned is [[1, 4], [2, 5], [3, 6]]. grid is unchanged, because map built new rows.

Copy a 2D array

A copy of the outer array still shares the row arrays. Spread and slice both do that. Copying each row as well gives independent rows of numbers. structuredClone deep-copies the nested arrays. Node.js 17.0.0 added that function as a global, and browsers have had it since March 2022. It throws DataCloneError when a value cannot be cloned.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const spreadCopy = [...grid];
const sliced = grid.slice();
const copied = grid.map((row) => [...row]);
const cloned = structuredClone(grid);

spreadCopy[0][0] = 99;
copied[0][0] = 5;
cloned[1][1] = 0;

spreadCopy and sliced are new outer arrays, and both still point at the original rows. spreadCopy[0] === grid[0] is true, and so is sliced[0] === grid[0]. Writing 99 through spreadCopy[0] changes grid[0], so grid[0][0] is 99 and sliced[0][0] is 99 too. copied was built from new row arrays before that write. copied[0][0] is 5, and that write does not change grid. cloned[1][1] is 0. grid[1][1] is still 5.

If a cell is an object, row => [...row] copies the reference to that object. structuredClone copies the object too, as long as the value is something the structured clone algorithm accepts.

Sort a 2D array

sort reorders the array you call it on and returns that same array. With no compare function, it turns elements into strings and compares those strings. [2, 10, 1].sort() becomes [1, 10, 2], because the string "10" comes before the string "2". A numeric compare function is (a, b) => a - b. A negative result puts a first.

To reorder rows without reordering the original outer array, copy the outer array first. That copy still shares the row objects.

const rows = [
  [3, 1],
  [1, 2],
  [2, 0],
];
const bySecond = [...rows].sort((a, b) => a[1] - b[1]);

The compare function reads index 1 of each row. 0 comes before 1, and 1 comes before 2. bySecond is [[2, 0], [3, 1], [1, 2]]. rows is still [[3, 1], [1, 2], [2, 0]]. bySecond[0] === rows[2] is true.

To sort inside each row and keep the original cells in place, copy the row before sorting it.

const rows = [
  [3, 1],
  [1, 2],
  [2, 0],
];
const sortedInside = rows.map((row) => [...row].sort((a, b) => a - b));

Each sort runs on a new two-element array. sortedInside is [[1, 3], [1, 2], [0, 2]]. rows is still [[3, 1], [1, 2], [2, 0]].

Add and remove rows and columns

push adds to the end. unshift adds to the beginning. pop removes the last row. splice(index, 1) removes one row at that index. The same methods work on a row when you want a column at the end, or when you want one column removed.

const matrix = [[1], [2]];
matrix.push([3]);
matrix.unshift([0]);
matrix.pop();
matrix.splice(0, 1);
matrix.forEach((row) => {
  row.push(9);
});
matrix.forEach((row) => {
  row.splice(0, 1);
});

After push and unshift, matrix is [[0], [1], [2], [3]]. pop removes [3]. splice(0, 1) removes [0], leaving [[1], [2]]. The first forEach pushes 9 onto each row, leaving [[1, 9], [2, 9]]. The second forEach removes index 0 of each row, leaving [[9], [9]].

push, pop, splice, fill, and sort change the array they are called on. map, slice, and flat return a new array. A function that receives a row and calls push on it changes the caller’s row, because the parameter and the caller’s slot are the same array.

function append(row, value) {
  row.push(value);
}

const matrix = [[1], [2]];
append(matrix[0], 9);

append pushes 9 onto [1]. matrix is [[1, 9], [2]].

Off-by-one indexes

The last row is matrix[matrix.length - 1], not matrix[matrix.length]. The second of those is undefined. Reading a cell from it throws, which is the TypeError from the access section.

A loop that assumes every row has matrix[0].length cells will read undefined on a shorter row, or skip cells on a longer one. Use matrix[r].length unless you have already checked that the matrix is rectangular.

One flat array

Each row of a nested grid is its own array object. You can store the same cells in one array and compute the index as row * cols + col.

const cols = 3;
const flat = [1, 2, 3, 4, 5, 6];
const cell = flat[1 * cols + 2];

Row 1, column 2 is index 1 * 3 + 2, which is 5. cell is 6.

A Float64Array stores 64-bit floating-point numbers in one buffer. An Int32Array stores 32-bit integers. The length is fixed when you create the array. new Float64Array(n) starts filled with 0. Setting an index past that length does not grow it, and there is no push on the typed array.

const cols = 3;
const typed = new Float64Array([1, 2, 3, 4, 5, 6]);
const cell = typed[1 * cols + 2];
typed[6] = 9;

cell is 6. typed.length stays 6, and typed[6] stays undefined.

When the size is known ahead of time, create the rows once and assign cells by index. A loop that runs [] and push on every pass allocates a new array each time that line runs.

Tic-tac-toe

A 3 by 3 board can start with null in every cell. A move writes "X" or "O" at board[row][col]. A line of three matching marks is a win. The lines are the three rows, the three columns, and the two diagonals.

const board = [
  ["X", null, "O"],
  [null, "X", null],
  ["O", null, "X"],
];

function winner(board) {
  const lines = [
    board[0],
    board[1],
    board[2],
    [board[0][0], board[1][0], board[2][0]],
    [board[0][1], board[1][1], board[2][1]],
    [board[0][2], board[1][2], board[2][2]],
    [board[0][0], board[1][1], board[2][2]],
    [board[0][2], board[1][1], board[2][0]],
  ];
  for (const line of lines) {
    if (line[0] && line[0] === line[1] && line[1] === line[2]) {
      return line[0];
    }
  }
  return null;
}

const mark = winner(board);

The main diagonal is "X", "X", "X". line[0] is truthy, and it equals the other two cells, so mark is "X". null is falsy, so an empty line does not count as three equal cells. A row of three "O" values returns "O".

Matrix multiplication

For matrices a and b, the cell result[i][j] is the sum of a[i][k] * b[k][j] over every k. That sum exists when the number of columns in a equals the number of rows in b. This function assumes both inputs are rectangular and that those sizes match.

function multiply(a, b) {
  const rows = a.length;
  const shared = a[0].length;
  const cols = b[0].length;
  const out = Array.from({ length: rows }, () => Array(cols).fill(0));
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      let sum = 0;
      for (let k = 0; k < shared; k++) {
        sum += a[i][k] * b[k][j];
      }
      out[i][j] = sum;
    }
  }
  return out;
}

const product = multiply(
  [
    [1, 2],
    [3, 4],
  ],
  [
    [5, 6],
    [7, 8],
  ]
);

a is 2 by 2 and b is 2 by 2, so shared is 2 and out is 2 by 2. For i = 0 and j = 0, the inner loop adds 1 * 5 and 2 * 7, which is 19. For i = 0 and j = 1, it adds 1 * 6 and 2 * 8, which is 22. The second result row is 3 * 5 + 4 * 7 and 3 * 6 + 4 * 8. product is [[19, 22], [43, 50]].

Rotate a matrix 90 degrees

A clockwise quarter turn sends matrix[r][c] to result[c][rows - 1 - r]. A grid with rows rows and cols columns becomes a grid with cols rows and rows columns. This function assumes a rectangular matrix with at least one row.

function rotateClockwise(matrix) {
  const rows = matrix.length;
  const cols = matrix[0].length;
  const out = Array.from({ length: cols }, () => Array(rows));
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      out[c][rows - 1 - r] = matrix[r][c];
    }
  }
  return out;
}

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const turned = rotateClockwise(grid);

1 is row 0, column 0, so it lands at column 0, row 3 - 1 - 0, which is out[0][2]. 3 lands at out[2][2]. 7 lands at out[0][0]. turned is [[7, 4, 1], [8, 5, 2], [9, 6, 3]].

The same turn is a transpose followed by reversing each new row. reverse changes the array it is called on, so call it on the new row that map just built.

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
const turned = Array.from({ length: grid[0].length }, (_, c) =>
  grid.map((row) => row[c]).reverse()
);

Column 0 maps to [1, 4, 7], and reverse makes it [7, 4, 1]. The other columns become [8, 5, 2] and [9, 6, 3]. turned matches the loop above. grid is unchanged.

Adjacency matrix

An adjacency matrix for n nodes is an n by n grid of numbers. graph[from][to] = 1 means an edge from from to to. A directed edge sets one cell. An undirected edge sets both graph[from][to] and graph[to][from].

const graph = Array.from({ length: 3 }, () => Array(3).fill(0));
graph[0][1] = 1;

Every cell starts at 0. The assignment records an edge from node 0 to node 1. graph is [[0, 1, 0], [0, 0, 0], [0, 0, 0]].

A sparse graph can store neighbors instead of a full square. This list has an edge from 0 to 1 and an edge from 2 to 0.

const neighbors = [[1], [], [0]];

neighbors[0] is the list of nodes reached from node 0. neighbors[1] is empty. The rows have different lengths, which a nested array allows.

If this article was helpful, tweet it!