Zero Array Algorithm not clearing correct columns

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);

In your if statement do this:

if (rowsToZero.includes(i)) { ... }
if (rowsToZero.includes(j)) { ... }

The in keyword works on the objects so its checking if the key (know as index’s in an array) is present. Since both the rowsToZero and the colsToZero have two items it returns true on the first two columns and rows since they both include index 0 and 1. Hope this helps.

Thank you so much, that was exactly the issue!