JavaScript Update specific index in a boolean matrix?

To update a specific index in a boolean matrix in JavaScript, you can directly access the element using array indexing and assign a new boolean value. Let's explore different approaches to create and modify boolean matrices.

Creating a Boolean Matrix

First, let's create a boolean matrix using the fill() method:

const array = Array(4);
var fillWithTrueValue = array.fill(true);
const matrixWithOnlyBooleanTrue = Array(4).fill(fillWithTrueValue);
console.log("Original matrix:");
console.log(matrixWithOnlyBooleanTrue);
Original matrix:
[
  [ true, true, true, true ],
  [ true, true, true, true ],
  [ true, true, true, true ],
  [ true, true, true, true ]
]

Problem with fill() Method

The above approach has a major issue - all rows reference the same array. Modifying one element affects all rows:

const array = Array(4).fill(true);
const matrix = Array(4).fill(array);

// Update index [0][1]
matrix[0][1] = false;

console.log("After updating [0][1]:");
console.log(matrix);
After updating [0][1]:
[
  [ true, false, true, true ],
  [ true, false, true, true ],
  [ true, false, true, true ],
  [ true, false, true, true ]
]

Correct Way to Create Independent Rows

Use Array.from() with a mapping function to create independent rows:

// Create 4x4 boolean matrix with independent rows
const matrix = Array.from({ length: 4 }, () => Array(4).fill(true));

console.log("Matrix with independent rows:");
console.log(matrix);

// Update specific index [1][2] to false
matrix[1][2] = false;

console.log("\nAfter updating [1][2] to false:");
console.log(matrix);
Matrix with independent rows:
[
  [ true, true, true, true ],
  [ true, true, true, true ],
  [ true, true, true, true ],
  [ true, true, true, true ]
]

After updating [1][2] to false:
[
  [ true, true, true, true ],
  [ true, true, false, true ],
  [ true, true, true, true ],
  [ true, true, true, true ]
]

Multiple Index Updates

You can update multiple indices in a single operation:

const matrix = Array.from({ length: 3 }, () => Array(3).fill(true));

// Update multiple specific indices
matrix[0][0] = false;
matrix[1][1] = false;
matrix[2][2] = false;

console.log("Matrix after diagonal updates:");
console.log(matrix);
Matrix after diagonal updates:
[
  [ false, true, true ],
  [ true, false, true ],
  [ true, true, false ]
]

Conclusion

Use Array.from() with a mapping function to create boolean matrices with independent rows. You can then update specific indices using standard array notation matrix[row][col] = newValue.

Updated on: 2026-03-15T23:18:59+05:30

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements