Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Resize multidirectional arrays JavaScript Google script

I need to resize arrays by adding empty new columns and empty new rows.

Ex

newRows = 2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

newCols = 3

(1s are just placeholder for any data)
arr= [ 
     [1,1,1,1],
     [1,1,1,1],
     [1,1,1,1],
    ];

To

arr= [ 
      [1,1,1,1,"","",""],
      [1,1,1,1,"","",""],
      [1,1,1,1,"","",""],
      ["","","","","","",""],
      ["","","","","","",""],
     ];

I can get the new empty cols but not the new empty rows

function resizeArr() {

let  arr= [ 
      [1,1,1,1],
      [1,1,1,1],
      [1,1,1,1],
     ];

let newCols =3 
    newRows = 2;
  
  //Add new empty cols
  arr.forEach((row) => {
    row[arr.length+newCols]="";
  });

  console.log(arr)
}

How to add new empty rows ?

Thanks

>Solution :

let arr = [
  [1,1,1,1],
  [1,1,1,1],
  [1,1,1,1],
];

let newCols = 3, newRows = 2

arr.forEach(i=>i.push(...Array(newCols).fill('')))
for(let i=0; i<newRows; i++) arr.push(Array(arr[0].length).fill(''))

console.log(arr)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading