简体   繁体   中英

Google Apps Script Better Way to Get Unique Values

I have working code that takes data from two non-adjacent columns in a Google Spreadsheet, looks for unique values in the first column, and if unique creates a new array with the unique value from the first column and corresponding value in the second column. The problem is, the data I am using is already somewhat long (413 rows) and will only get longer over time. It takes about 1-2 minutes for the code to run through it. I've been looking for a shorter way to do this and I've come across the filter() and map() array functions which are supposedly faster than a for loop but I can't get them implemented correctly. Any help with these or a faster method would be greatly appreciated. The code I have right now is below.

function getkhanassignments(rows) {

  var assignmentsraw = [];
  var temparray = [];
  var previousassignment = datasheet.getRange(50,1).getValue();
  for(i=0, j=0;i<rows-1;i++) {
    if(datasheet.getRange(50+i,1).getValue() != previousassignment) {   
      previousassignment = datasheet.getRange(50+i,1).getValue();
      assignmentsraw[j] = new Array(2);
      assignmentsraw[j][0] = datasheet.getRange(50+i,1).getValue();
      assignmentsraw[j][1] = datasheet.getRange(50+i,8).getValue();
      j++;
    }
  }
  Logger.log(assignmentsraw);
  return assignmentsraw;
}

The answers I've found elsewhere involve just getting unique values from a 1d array whereas I need unique values from a 1d combine with corresponding values from another 1d array. The output should be a 2d array with unique values from the first column and their corresponding values in the second column.

Solution:

The best practice of looping through ranges in Google Apps Script is to dump the range values into a 2D array, loop through that array, and then return the output array back to Google Sheets.

This way, there would be no calls to Sheets API inside loops.

Sample Code:

function getkhanassignments(rows) {

  var assignmentsraw = [];

  var table1 = datasheet.getRange(50,1,rows).getValues();
  var table2 = datasheet.getRange(50,8,rows).getValues();

  var previousassignment = table1[0][0];
  assignmentsraw.push([table1[0][0],table2[0][0]]);
  for(i=0; i<rows; i++) {
    if (table1[i][0] != previousassignment) {
      assignmentsraw.push([table1[i][0],table2[i][0]]);
      previousassignment = table1[i][0];
    }
  }
  Logger.log(assignmentsraw);
  return assignmentsraw;
}

References:

Class Range

push()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM