I learned how to pre-fill/pre-dimension a 2D array! It was part of an Exercism challenge.
I had tried things like
var a = Array(3).fill(Array(2).fill(0))
but when you do something like
a[0][1] = "dog";
you get an array that looks like
[[0,"dog"], [0,"dog"], [0,"dog"]]
So what one has to do is to Array(3).fill(0)
and then .map
the array to another Array(2).fill(0)
as per the following fragment from my Exercism solution:
rotate(array) {
const [rowMax, colMax] = [array.length, array[0].length];
const result = Array(colMax)
.fill(0)
.map(() => Array(rowMax).fill(0));
for (let col = 0; col < rowMax; col++) {
for (let row = 0; row < colMax; row++) {
result[row][col] = array[col][row];
}
}
return result;
}
specifically the
Array(colMax)
.fill(0)
.map(() => Array(rowMax).fill(0));
part
Top comments (0)