Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get first column in array

I have a sheet and need to get the values (email addresses) of a certain column, which is C in this case. Let's assume there are three emails in the column. The log gives me:

"[[email1], [email2], [email3]]"

In order to continue with the script I need to have the array looking like this:

"[email1, email2, email3]"

So just without the outer brackets. I know I can target just "[email1]" by adding "[0]" behind ".getValues()". I tried something like "[[all]]" but it didn't work. What do I have to change? I know, this is probably pretty basic but I'm an absolute beginner, thankful for any help.

function myFunction() {

  // Variables
  var id = "ID";
  var spreadSheet = SpreadsheetApp.openById(id);
  var inputSheet = spreadSheet.getSheetByName("inputSheet");
  var inputLR = inputSheet.getLastRow();
  var emailsAll = inputSheet.getRange(2, 3, inputLR).getValues();

  Logger.log(emailsAll);
}
like image 405
hupfhupf Avatar asked Oct 19 '18 15:10

hupfhupf


2 Answers

V8 update(ES6):

Use Array#flat:

var em = emailsAll.flat();//[[e],[e],[e]]=>[e,e,e]

Try Array#map or Array#forEach

var em = emailsAll.map(function(e){return e[0];});//[[e],[e],[e]]=>[e,e,e]
like image 95
TheMaster Avatar answered Sep 28 '22 17:09

TheMaster


getValues() return a two-dimensional array representing the rows and columns in the range. Read more in the developer reference.

Iterate over this array to access the values.

for(var row=0;row<emailsAll.length;row++){
   for(var col=0;col<emailsAll[row].length;col++){
      var cellValue = emailsAll[row][col];
      Logger.log(cellValue);
   }
}

Reference material about for loops here and here.

Example in plain js:

var emailsAll = [["email1"],["email2"],["email3"]];
for(var row=0;row<emailsAll.length;row++){
  for(var col=0;col<emailsAll[row].length;col++){
    var cellValue = emailsAll[row][col];
    console.log(cellValue);
  }
}
like image 25
rckrd Avatar answered Sep 28 '22 16:09

rckrd