0

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"]]
roipoussiere
  • 5,142
  • 3
  • 28
  • 37
  • 1
    Are you sure you want `array[i].push( ... addedArray )` instead of just `array[i].push( addedArray )`? – Dai Oct 19 '18 at 16:30
  • Yes, because without `...` I get `[[0,0,[1,1],[1,1]],[0,0,[1,1],[1,1]]]`, but I want `[[0,0,1,1],[0,0,1,1]]` – roipoussiere Oct 19 '18 at 16:33
  • 1
    `push`doesn't add the elements on two arrays. Your problem is that your outer array contains the same *one* inner array multiple times. – Bergi Oct 19 '18 at 16:53
  • @Bergi about the duplicate I edited my question, now the array is initialized correctly, but I still use `fill()` in `addColumns()` and `addRows()`, I'm investigating this according to your last comment. – roipoussiere Oct 19 '18 at 18:01
  • I fixed it by replacing the content in addColumns by `array.push(...Array.from({ length: number }, () => new Array(array[0].length).fill(value)));`. Thank you. – roipoussiere Oct 19 '18 at 18:13

0 Answers0