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

How to paste a 2D array (with headers) into another sheet with column headers randomly set using GAS?

The data:

[
 ["ID","Variação","Nome Site","Obs"],//Headers
 [11602,185,"Camisa Teste","Teste da Observação"] //To be pasted
]

This is how the destination is:

Obs Nome Site Variação ID

I understand I could take the approach below, but considering that the dataset has more then 40 columns, this is not that feasible:

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

var data = sheet.getRange(1,1,2,4).getValues();
var obs = data.map(function(e){return e[0];});
var NomeSite = data.map(function(e){return e[1];});
...

How would I go about finding the header and "pasting" the data in that case?

Thank you!

>Solution :

I believe your goal is as follows.

  • You want to rearrange the values by your expected header.

In this case, how about the following modification?

Modified script:

var expectedHeader = ["Obs", "Nome Site", "Variação", "ID"]; // Please set your expected header.

// This sample value is from your question.
var data = [
  ["ID", "Variação", "Nome Site", "Obs"],
  [11602, 185, "Camisa Teste", "Teste da Observação"]
];

var [headers, ...rows] = data;
const obj = rows.map(r => headers.reduce((o, h, j) => (o[h] = r[j], o), {}));
var res = obj.map(o => expectedHeader.map(h => o[h] || ""));
console.log(res) // [["Teste da Observação","Camisa Teste",185,11602]]
  • When this script is used, [11602, 185, "Camisa Teste", "Teste da Observação"] is rearranged to ["Teste da Observação","Camisa Teste",185,11602].

References:

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