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

Google Sheet Script – Applying 2d array with different size sub arrays to Sheet

I’ve parsed a json response from an API to a 2d array
and now that I’ve built the array I want to display it on my sheet however This is my dataarray
It has 413 rows and those rows have varying amounts of data (row 0 is the header row with 67 fields, but not every row has all 67 fields of data in it)

enter image description here

This is the code I’m using to try and write the data to my sheet (shProductData is a variable I defined earlier in the code to identify my sheet)

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

shProductData.getRange(1,1,dataArray.length,dataArray[0].length).setValues(dataArray);

However I get the error:

Exception: The number of columns in the data does not match the number of columns in the range. The data has 40 but the range has 67.

It writes the header row to my sheet first but then fails on the next one. Is there any way around this? Or am I going to somehow make my sub arrays all be 67 in size?

>Solution :

You can add empty cells at the end of short rows in the data this way:

var data = [
    [1,2,3],
    [4,5],
    [6,]
]

// get max length of rows in the data
var max_length = Math.max(...data.map(x => x.length));

// add empty cells at end of short rows
data.forEach(row => { while (row.length < max_length) row.push('') } )

console.log(data); // output: [ [ 1, 2, 3 ], [ 4, 5, '' ], [ 6, '', '' ] ]
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