Skip to main content

Working with Two-Dimensional Arrays

1. Creating 2D Arrays

Method Description Example
Array constructor Creates a 2D array with specified dimensions const arr = Array(3).fill().map(() => Array(4).fill(0));
Nested loops Manually initialize each element let arr = [];\nfor (let i = 0; i < 3; i++) {\n arr[i] = [];\n for (let j = 0; j < 4; j++) {\n arr[i][j] = 0;\n }\n}
Array.from() Creates a 2D array using a mapping function const arr = Array.from({ length: 3 }, () => Array(4).fill(null));

Example: Initialize with default values

const matrix = Array(3).fill().map(() => Array(3).fill(0));\nconsole.log(matrix);\n// Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

2. Accessing Elements

Access Method Description Example
row[col] Access element at row index and column index
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(matrix[1][2]); // Output: 6
row.length Get number of columns in a specific row
let matrix = [[1, 2, 3], [4, 5, 6]];
console.log(matrix[0].length); // Output: 3
matrix.length Get number of rows in the matrix
let matrix = [[1, 2, 3], [4, 5, 6]];
console.log(matrix.length); // Output: 2

3. Iterating 2D Arrays

Example: Row-by-Row Iteration

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

for (let i = 0; i < matrix.length; i++) {
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(matrix[i][j]);
  }
}
Iteration Method Description Use Case
Nested Loops Using two for loops to traverse rows and columns Basic traversal, accessing each element by index
for...of with Nested Loops Using for...of to iterate over rows and columns Readable code when element values are needed directly
Flat Map Flattening the 2D array and mapping over elements Transforming all elements into a new structure

Example: Using for...of

const matrix = [
  [1, 2],
  [3, 4]
];

for (const row of matrix) {
  for (const element of row) {
    console.log(element);
  }
}

Example: Flattening and Mapping

const matrix = [
  [1, 2],
  [3, 4]
];

const flatMapped = matrix.flat().map(x => x * 2);
console.log(flatMapped); // [2, 4, 6, 8]

4. Traversing Matrix

Example: Traverse Matrix in Spiral Order

function spiralOrder(matrix) {
  if (!matrix || matrix.length === 0 || matrix[0].length === 0) return [];

  const result = [];
  let top = 0;
  let bottom = matrix.length - 1;
  let left = 0;
  let right = matrix[0].length - 1;

  while (top <= bottom && left <= right) {
    // Traverse right
    for (let i = left; i <= right; i++) {
      result.push(matrix[top][i]);
    }
    top++;

    // Traverse down
    for (let i = top; i <= bottom; i++) {
      result.push(matrix[i][right]);
    }
    right--;

    // Traverse left (if row still exists)
    if (top <= bottom) {
      for (let i = right; i >= left; i--) {
        result.push(matrix[bottom][i]);
      }
      bottom--;
    }

    // Traverse up (if column still exists)
    if (left <= right) {
      for (let i = bottom; i >= top; i--) {
        result.push(matrix[i][left]);
      }
      left++;
    }
  }

  return result;
}

// Example usage:
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
console.log(spiralOrder(matrix)); // [1, 2, 3, 6, 9, 8, 7, 4, 5]
Traversal Method Description Time Complexity Space Complexity
Spiral Order Traverse elements in spiral from outer to inner layers O(m*n) O(1) (excluding output array)
Row-wise Traverse elements row by row from left to right O(m*n) O(1)
Column-wise Traverse elements column by column from top to bottom O(m*n) O(1)
Diagonal Traverse elements along diagonals (main and anti) O(m*n) O(1)
Note: Spiral traversal requires careful boundary management to avoid revisiting elements.

Example: Diagonal Traversal

function diagonalTraversal(matrix) {
  if (!matrix || matrix.length === 0) return [];

  const result = [];
  const rows = matrix.length;
  const cols = matrix[0].length;

  // Main diagonal (top-left to bottom-right)
  for (let i = 0; i < Math.min(rows, cols); i++) {
    result.push(matrix[i][i]);
  }

  // Anti-diagonal (top-right to bottom-left)
  for (let i = 0; i < Math.min(rows, cols); i++) {
    result.push(matrix[i][cols - 1 - i]);
  }

  return result;
}

// Example usage:
const matrix2 = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
console.log(diagonalTraversal(matrix2)); // [1, 5, 9, 3, 5, 7]

5. Implementing Diagonal Traversal

Diagonal traversal of a 2D array involves visiting elements along diagonals, typically from top-left to bottom-right. This is useful in algorithms like matrix traversal or specific graph problems.

Method Description Time Complexity Space Complexity
Top-Left to Bottom-Right Traverse elements where row + col is constant O(m * n) O(1)
Bottom-Left to Top-Right Traverse elements where row - col is constant O(m * n) O(1)

Example: Top-Left to Bottom-Right Traversal

function diagonalTraversal(matrix) {
  const result = [];
  const rows = matrix.length;
  const cols = matrix[0].length;

  for (let sum = 0; sum <= rows + cols - 2; sum++) {
    const startRow = Math.max(0, sum - cols + 1);
    const endRow = Math.min(sum, rows - 1);

    for (let row = startRow; row <= endRow; row++) {
      const col = sum - row;
      if (col >= 0 && col < cols) {
        result.push(matrix[row][col]);
      }
    }
  }

  return result;
}

// Example usage:
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(diagonalTraversal(matrix)); // [1, 2, 4, 7, 5, 3, 6, 8, 9]

Example: Bottom-Left to Top-Right Traversal

function antiDiagonalTraversal(matrix) {
  const result = [];
  const rows = matrix.length;
  const cols = matrix[0].length;

  for (let diff = -cols + 1; diff <= rows - 1; diff++) {
    const startRow = Math.max(0, -diff);
    const endRow = Math.min(rows - 1, rows - 1 - diff);

    for (let row = startRow; row <= endRow; row++) {
      const col = row + diff;
      if (col >= 0 && col < cols) {
        result.push(matrix[row][col]);
      }
    }
  }

  return result;
}

// Example usage:
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(antiDiagonalTraversal(matrix)); // [3, 2, 4, 1, 5, 7, 6, 8, 9]

6. Implementing Spiral Traversal

Spiral traversal (also known as spiral matrix traversal) involves visiting all elements of a 2D array in a spiral pattern starting from the top-left corner, moving right, then down, then left, then up, and repeating inward.

Operation Description Time Complexity Space Complexity
Spiral Traversal Traverses 2D array in spiral order O(m × n) O(1) (excluding output array)

Example: Spiral Traversal of a 3x3 Matrix

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

function spiralOrder(matrix) {
  const result = [];
  if (!matrix || matrix.length === 0 || matrix[0].length === 0) return result;

  let top = 0;
  let bottom = matrix.length - 1;
  let left = 0;
  let right = matrix[0].length - 1;

  while (top <= bottom && left <= right) {
    // Traverse Right
    for (let i = left; i <= right; i++) {
      result.push(matrix[top][i]);
    }
    top++;

    // Traverse Down
    for (let i = top; i <= bottom; i++) {
      result.push(matrix[i][right]);
    }
    right--;

    // Traverse Left (if row still valid)
    if (top <= bottom) {
      for (let i = right; i >= left; i--) {
        result.push(matrix[bottom][i]);
      }
      bottom--;
    }

    // Traverse Up (if column still valid)
    if (left <= right) {
      for (let i = bottom; i >= top; i--) {
        result.push(matrix[i][left]);
      }
      left++;
    }
  }

  return result;
}

console.log(spiralOrder(matrix)); // [1, 2, 3, 6, 9, 8, 7, 4, 5]
Note: The spiral traversal algorithm uses boundary pointers to keep track of the current edges of the matrix. These are updated after each side is traversed.

7. Rotating Matrix

Example: Rotate 90 Degrees Clockwise

function rotateMatrix(matrix) {
  const n = matrix.length;
  const rotated = [];

  for (let i = 0; i < n; i++) {
    rotated[i] = [];
    for (let j = 0; j < n; j++) {
      rotated[i][j] = matrix[n - 1 - j][i];
    }
  }

  return rotated;
}

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

const rotated = rotateMatrix(matrix);
console.log(rotated);
// Output:
// [
//   [7, 4, 1],
//   [8, 5, 2],
//   [9, 6, 3]
// ]
Operation Description Time Complexity Space Complexity
90° Clockwise Rotation Transpose and reverse each row O(n^2) O(n^2)
180° Rotation Reverse rows and then transpose O(n^2) O(n^2)
270° Clockwise Rotation Transpose and reverse columns O(n^2) O(n^2)
Note: For in-place rotation, use O(1) space by swapping elements layer by layer.

8. Transposing Matrix

Example: Transpose a 3x3 Matrix

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

const transposed = matrix[0].map((_, colIndex) =>
  matrix.map(row => row[colIndex])
);

console.log(transposed);
// Output:
// [
//   [1, 4, 7],
//   [2, 5, 8],
//   [3, 6, 9]
// ]
Operation Description Time Complexity Space Complexity
Transpose Convert rows to columns and vice versa O(n*m) O(n*m)
Note: For a square matrix, in-place transpose can be done with O(1) space by swapping elements across the diagonal.

9. Flattening 2D Arrays

Example: Flattening a 2D Array Using flat()

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

const flattened = matrix.flat();
console.log(flattened); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Method Description Example
flat() Flattens nested arrays up to a specified depth (default is 1). [[1, 2], [3, 4]].flat(); // [1, 2, 3, 4]
flat(Infinity) Flattens all nested levels. [[1, [2, 3]], [4, [5, 6]]].flat(Infinity); // [1, 2, 3, 4, 5, 6]
reduce() Flattens using a reducer function. [[1, 2], [3, 4]].reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4]
Note: flat() is a built-in method in ES2019 and later.

Example: Flattening with reduce() and concat()

const matrix = [
  [1, 2],
  [3, 4],
  [5, 6]
];

const flattened = matrix.reduce((acc, row) => acc.concat(row), []);
console.log(flattened); // [1, 2, 3, 4, 5, 6]

Was this article helpful?