0

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?

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]);
        }
      }
    }
  }
}
2
  • Put the values you want to push into the array like this larray.push([data[j][i], data[j][i+1]]). That will make a row of two values. Commented Mar 28, 2022 at 17:26
  • @TheWizEd Sigh. The coffee is not as strong as it needs to be this fine Monday morning. Can you please answer it so that I can give you the credit for an answer, then go hide my head in shame? Commented Mar 28, 2022 at 17:31

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.