Doing a portion of a leetcode problem, and this is my JS code where I want to insert rows and columns:
var maxIncreaseKeepingSkyline = function(grid) {
let newGrid = [...Array(grid.length)].fill([]);
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[i].length; j++) {
newGrid[i].push(grid[j][i]);
}
}
console.log(newGrid);
};
console.log(maxIncreaseKeepingSkyline([[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]));
Ideally, it would produce 4 diff arrays with 4 elements in each array, but for some reason, it produces 4 identical arrays with 16 elements each. It does produce the correct order that I am looking for, but it is not placed in the right arrays (all 0th elements of the grid to the 0th element of new grid, all 1st elements of the grid to the 1st element of the new grid, and so on is what I'm looking for).
My debugger shows that i (outer loop) and j (inner loop) does increment properly, but my function seems to push to all 4 arrays within new grid at the same time and it disregards the 'i' variable in my newGrid[i].push(...)
. Not sure why it is doing that.
When you use fill([])
, you're filling each element with the same empty array. Since objects are essentially references to memory locations in Javascript, when you alter any of the newGrid
sub-arrays, you're actually altering all of them, since they all point to the same object.
const arr = new Array(2).fill({});
console.log(arr[0] === arr[1]);
Create a new array on each iteration instead with Array.from
's built-in map
:
const newGrid = Array.from({ length: grid.length }, () => [])