I wrote these functions to add columns and rows to a 2D array:
function addColumns(array, number, value) {
array.push(...new Array(number).fill(new Array(array[0].length).fill(value)));
return array;
}
function addRows(array, number, value) {
array.map((e) => { e.push(...new Array(number).fill(value)); return e; });
return array;
}
And now I want to use them on a 2x2 array:
let myArray = [...new Array(2)].map(() => new Array(2).fill('a'));
console.log(`init: ${JSON.stringify(myArray)}`);
myArray = addColumns(myArray, 2, 'b');
console.log(`added 2 columns: ${JSON.stringify(myArray)}`);
myArray = addRows(myArray, 2, 'c');
console.log(`added 2 rows: ${JSON.stringify(myArray)}`);
console.log('expected: [["a","a","c","c"],["a","a","c","c"],["b","b","c","c"],["b","b","c","c"]]');
I don't understand the result, I was expecting an array of 4x4 array.
init: [["a","a"],["a","a"]]
added 2 columns: [["a","a"],["a","a"],["b","b"],["b","b"]]
added 2 rows: [["a","a","c","c"],["a","a","c","c"],["b","b","c","c","c","c"],["b","b","c","c","c","c"]]
expected: [["a","a","c","c"],["a","a","c","c"],["b","b","c","c"],["b","b","c","c"]]