Kramar
Kramar

Reputation: 93

Arrays in Google Scripts

I am struggling with arrays in google scripts. Let's say I have range: "A1:B4".
|Column A|column B|
|name1 |value1|
|name1 |value2|
|name2 |value3|
|name2 |value4|

 var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Arkusz1");
 var range = ss.getRange("A1:B4").getValues();
 var array = [[]];

So, I have to do an array that would look like this:

 array[0] = name1
 array[0][0] = value1
 array[0][1] = value2
 array[1] = name2
 array[1][0] = value3
 array[1][1] = value4

I made this

 for(var i = 0; i < range.length; i++)
 {
    array[i] = range [i][0];
    for(var j = 0; j < range[i].length; j++)
    {
      array[i][j] = range[i][j];  
    }   
 }

And I am getting on the second dimension I am getting first chars from the first dimension and I cannot change the value after it, e.g. Instead of value1 on:

array[0][0]

I have n only (the first letter from name1)

I will appreciate any idea.

@EDIT
enter image description here

Ok, thank You all for answers but it is not it (or I am too stupid to understand). I have this table, what I need to do is make one array where car1 is array[0], car2 is array[1] etc and every value in B is unique date ( array[0][0] -> one date for car1, array[0][1] different day but still for car1 and then, in the third dimension summed up all values from column C but with depends on same date. I hope it is clear enough.

Upvotes: 1

Views: 14654

Answers (3)

tehhowch
tehhowch

Reputation: 9872

Your issue is that a "2D" Javascript array (i.e. an array in Google Apps Script) has no values in the first dimension. The first dimension is simply the row of data you are working on, in the form of an array of values. All data is in this inner array:

var arr = sheet.getDataRange().getValues();
for (var r = 0, numRows = arr.length; r < numRows; ++r) {
  // This will log an Array, e.g. [Car1, timestamp, 1324], in a single line.
  Logger.log(arr[r]);
  // This loop over the inner array will log Car1, then timestamp, then 1323, each on its own line.
  for (var c = 0, numCols = arr[0].length; c < numCols; ++c)
    Logger.log(arr[r][c]);
}

Your (rather unclear) intended use seems to be solved most easily by using an Object, rather than an Array. An Object can have user-defined properties, which can themself contain properties. For instance, perhaps you want to assemble an Object that maps out all the different cars you have, and then for each car, you want to know which dates they were driven on, and how many miles were driven for each date. Constructing such an Object would look like this:

// Create an empty Javascript Object and read data from the sheet.
var carHistory = {}, data = sheet.getDataRange().getValues();
// Remove the header row from the data array.
var headers = data.splice(0, 1)[0];

// Determine the appropriate columns needed.
var carIndex = headers.indexOf("carId");
var dayIndex = headers.indexOf("Date Driven");
var milesIndex = headers.indexOf("Miles");

// Build the object by parsing all rows of data.
for (var r = 0; r < data.length; ++r) {
  var row = data[r], id = row[carIndex];

  // If this car has not been seen, add it, and initialize its properties.
  if (!carHistory[id]) carHistory[id] = {"total miles": 0, days: {}};

  // If this day has not been seen, add it.
  var drivenOn = row[dayIndex];
  /* Assumption: stored a string of the date that does not
     parse into a Date object (like a timestamp would) */
  if (!carHistory[id].days[drivenOn]) carHistory[id].days[drivenOn] = 0;

  // Increment the total and the daily miles.
  var miles = row[milesIndex];
  carHistory[id]["total miles"] += miles;
  carHistory[id].days[drivenOn] += miles;
}

// Log the report:
for (var car in carHistory) {
  Logger.log("%s drove %s total miles", car, carHistory[car]["total miles"]);
  for (var day in carHistory[car].days)
    Logger.log("%s drove %s on day %s", car, carHistory[car].days[day], day);
}

You should read more about objects in your preferred Javascript Developer Reference. One such reference is MDN.

Upvotes: 1

Brian
Brian

Reputation: 4344

The challenge is to combine arrays with potential identical values. You can use a recursive check to compare the arrays before combining.

function checkVal(a, b) {
  // Looping through will return a blank array on the last line. Break early.
  if(b !== undefined) {

    // Check the first value in each array. If they're the same, combine and return.
    if(a[0] == b[0]) {
      a.push(b[1])
      return a
    }
  }
}

function coerce() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet7")

  // This returns a 2D array
  var range = sheet.getDataRange().getValues();

  // Initialize a new array
  var array = [];

  for(var i=0; i<range.length; i++) {

   // Compare two rows
   var combined = checkVal(range[i], range[i+1])

   // If you get a new array, push it to [array]
   if(combined) { 
     array.push(combined) 
   }
  }
  Logger.log(array)  // Logs [[Name 1, Value 1, Value 2], [Name 2, Value 1, Value 2]]
}

Upvotes: 0

Darpan Sanghavi
Darpan Sanghavi

Reputation: 1413

Here's how you can do it,

function myFunction() {
 var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
 var range = ss.getDataRange().getValues();
 var array = [[]];

   for(var i = 0; i < range.length; i++)
   {
     array[i] = range [i];
   }
  Logger.log(array[0][0]); //prints A1
  Logger.log(array[0][1]); //prints B1
}

Here's the spreadsheet sample I've used.

enter image description here

Upvotes: 1

Related Questions