I am attempting to create a function that pads a 2D array with zeros. I have made the following function:
function addPadding(arr){
var a = new Array(arr.length + 2).fill(0)
//left and right padding
arr.forEach(el => {
el.push(0)
el.unshift(0)
})
//top padding
arr.unshift(a)
//bottom padding
arr.push(a)
return arr;
}
console.table(addPadding(addPadding([[1,2],[3,4]])));
The function works fine if I only call it once, but if I call it twice, like in this example, I get the following table:
My function has an unintended result, it has added extra zeroes for 2 rows. Does anyone know why this is happening?
The first time you are padding at top and bottom the same array a
. This means the second time that same array gets padded (left & right) twice.
Avoid adding the same array by taking a copy.
Change:
arr.push(a)
to:
arr.push([...a])