Home > Back-end >  Javascript 2D Array to two-2D Arrays
Javascript 2D Array to two-2D Arrays

Time:03-29

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]);
        }
      }
    }
  }
}

CodePudding user response:

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

  • Related