简体   繁体   中英

How do i translate SORT and Match google sheet formula into app script/ javascript?

How do I run a formula like:

=sort(A2:F5000, match(B2:B5000,{"QTA 10 Days","QTA-REMAKE","QTA-SAMPLE","QTA NEW PROJECT","QTA NPI-CVF-Bryan","Qual-QTA-NPI Remake"},0),1)

To a range of fields using the Google Apps Script API for Google Sheets?

To sort your sheet, you can use the following code:

function myFunction() {
  var inSheet = SpreadsheetApp.getActive().getSheets()[0];
  var outSheet = SpreadsheetApp.getActive().getSheets()[1];

  var values = inSheet.getRange('A2:C23').getValues();
  values.sort(mySort);

  outSheet.getRange('A2:C23').setValues(values);
}


function mySort(row1, row2) {
  var values = ["QTA 10 Days","QTA-REMAKE","QTA-SAMPLE","QTA NEW PROJECT","QTA NPI-CVF-Bryan","Qual-QTA-NPI Remake"];
  var val1 = values.indexOf(row1[2]);
  var val2 = values.indexOf(row2[2]);
  return val1 - val2;
}

You will of course have to change the ranges and/or sheets that you are using. The Sheets file I have used is this one, where you can see the original values in Sheet1 and the output of running my script in Sheet2.

Sorting based on starting pattern substring

To sort based on whether the string starts with "QTA" or not, you can substitute the mySort function I provided above with the following:

function mySort(row1, row2) {
  var val1 = row1[2];
  var val2 = row2[2];
  var qta1 = val1.indexOf("QTA") == 1;
  var qta2 = val2.indexOf("QTA") == 1;
  if (qta1 === qta2) return  strcmp(val1, val2);
  return qta1 ? 1 : -1;
}

function strcmp(a, b) {
  if (a.toString() < b.toString()) return -1;
  if (a.toString() > b.toString()) return 1;
  return 0;
}

This function will prioritise the rows that contain 'QTA', and it will also compare the rest of the the string in case both or neither contain the substring. See Sheet3 of my test sheet for the results.

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