How to zero out a matrix in JavaScript

Here is one way to zero out an MxN matrix in JavaScript. And by zero out this means that if an element in the matrix is 0, its entire row and column are set to 0.

Space complexity: O(1)
Time complexity: O(n^2)

zeroMatrixTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function zeroMatrix(matrix) {
let rowHasZero = false;
let colHasZero = false;
// Check if first row has a zero
for (let j = 0; j < matrix[0].length; j++) {
if (matrix[0][j] === 0) {
rowHasZero = true;
break;
}
}
// Check if first column has a zero
for (let i = 0; i < matrix.length; i++) {
if (matrix[i][0] === 0) {
colHasZero = true;
break;
}
}
// Check for zeroes in the rest of the array
for (let i = 1; i < matrix.length; i++) {
for (let j = 1; j < matrix[0].length; j++) {
if (matrix[i][j] === 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// Nullify rows based on values in first column
for (let i = 1; i < matrix.length; i++) {
if (matrix[i][0] === 0) {
nullifyRow(matrix, i);
}
}
// Nullify columns based on values in first row
for (let j = 1; j < matrix[0].length; j++) {
if (matrix[0][j] === 0) {
nullifyColumn(matrix, j);
}
}
// Nullify first row
if (rowHasZero) {
nullifyRow(matrix, 0);
}
// Nullify first column
if (colHasZero) {
nullifyColumn(matrix, 0);
}
return matrix;
}
function nullifyRow(matrix, i) {
for (let j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 0;
}
}
function nullifyColumn(matrix, j) {
for (let i = 0; i < matrix.length; i++) {
matrix[i][j] = 0;
}
}

Test cases can be found at REPL.it