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

Javascript 2D Array to two-2D Arrays

I’m in Google Apps Script. I grab all of the dta from a spreadsheet, "Documents". The top row is "Letters", "", "Templates", "". Column 1 has human readable descriptions of documents (e.g. "Letter to Client"). Column 2 has Google Docs IDs for the template. Column 3 goes back to human readable descriptions of memoranda, and column 4 has Google Docs IDs for the template.

My goal is to break the array generated from this sheet into two separate arrays, so that var larray = ["letter to client", "docID"] (and so on; there are about 10 rows of letters and 7 rows of memoranda). I need to be able to address, e.g., larray[4][1] and return the docID.

Here’s my script but for now I’m only getting a 1D array, not a 2D array. What am I missing to force larray into 2d?

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

function testArray(){
  var data = ssAF.getSheetByName('Documents').getDataRange().getValues();
  var larray = [];
  var marray = [];
  for(var i = 0; i < data.length; i++){
    if(data[0][i] == "Letters"){
      for (var j = 0; j < data.length; j++) {
        if (data[j][i] != "") {
          larray.push(data[j][i], data[j][i+1])
        }
      }
    }
    else if (data[0][i] == "Memoranda"){
      for (var j = 0; j < data.length; j++) {
        if (data[j][i] != "") {
          marray.push(data[j][i]);
        }
      }
    }
  }
}

>Solution :

Description

If larray = [], larray.push(a,b) will result in a 1D array [a,b]. And larray.push(c,d) becomes [a,b,c,d]. To make a 2D array use larray.push([a,b]), now larray is [[a,b]]. larray.push([c,d]) becomes [[a,b],[c,d]]

Script

function testArray(){
  var data = ssAF.getSheetByName('Documents').getDataRange().getValues();
  var larray = [];
  var marray = [];
  for(var i = 0; i < data.length; i++){
    if(data[0][i] == "Letters"){
      for (var j = 0; j < data.length; j++) {
        if (data[j][i] != "") {
          larray.push([data[j][i], data[j][i+1]])
        }
      }
    }
    else if (data[0][i] == "Memoranda"){
      for (var j = 0; j < data.length; j++) {
        if (data[j][i] != "") {
          marray.push([data[j][i]]);
        }
      }
    }
  }
}

Reference

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