I’m trying to write an algorithm such that if an element in an M x N matrix is 0, it’s entire row and column are set to 0. For example,

[

[0, 1, 2, 3],

[4, 5, 0, 6],

[7, 8, 9, 1],

[2, 3, 4, 5]

];

Would become:

[

[0, 0, 0, 0],

[0, 0, 0, 0],

[0, 8, 0, 1],

[0, 3, 0, 5]

];

I’ve figured out how to do as you can see in the codebyte below or in repo here:

However, even though in test A the columns to be zero’d are [0, 2] it constantly seems to be zeroing items of column 0 and 1. Grrrrrrr Anyone spot my error?

const testMatrixA = [
[0, 1, 2, 3],
[4, 5, 0, 6],
[7, 8, 9, 1],
[2, 3, 4, 5]
];
const zeroArray = (matrix) => {
const numOfRows = matrix.length;
const numOfCols = matrix[0].length;
const rowsToZero = [];
const colsToZero = [];
for (i = 0; i < numOfRows; i++) {
let arrayRow = matrix[i];
for (j = 0; j < numOfCols; j++) {
if (arrayRow[j] === 0) {
rowsToZero.push(i);
colsToZero.push(j);
}
}
}
for (i = 0; i < numOfRows; i++) {
let arrayRow = matrix[i];
for (j = 0; j < numOfCols; j++) {
if (i in rowsToZero) {
arrayRow[j] = 0;
};
if (j in colsToZero) {
arrayRow[j] = 0;
};
}
}
console.log('rows to Zero: ', rowsToZero);
console.log('cols to Zero: ', colsToZero);
console.log('Zerod Matrix: ', matrix);
};
zeroArray(testMatrixA);