Sort ranges in an array in google apps script

Posted by user1637113 on Stack Overflow See other posts from Stack Overflow or by user1637113
Published on 2012-08-30T21:36:41Z Indexed on 2012/08/30 21:38 UTC
Read the original article Hit count: 197

I have a timesheet spreadsheet for our company and I need to sort the employees by each timesheet block (15 rows by 20 columns). I have the following code which I had help with, but the array quits sorting once it comes to a block without an employee name (I would like these to be shuffled to the bottom). Another complication I am having is there are numerous formulas in these cells and when I run it as is, it removes them. I would like to keep these intact if at all possible. Here's the code:

function sortSections() 
{
  var activeSheet = SpreadsheetApp.getActiveSheet();
  //SETTINGS
  var sheetName = activeSheet.getSheetName(); //name of sheet to be sorted
  var headerRows = 53; //number of header rows
  var pageHeaderRows = 5; //page totals to top of next emp section
  var sortColumn = 11; //index of column to be sorted by; 1 = column A
  var pageSize = 65;
  var sectionSize = 15; //number of rows in each section

  var col = sortColumn-1;
  var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
  var data = sheet.getRange(headerRows+1, 1, sheet.getMaxRows()-headerRows, sheet.getLastColumn()).getValues();
  var data3d = [];
  var dataLength = data.length/sectionSize;
  for (var i = 0; i < dataLength; i++) {
    data3d[i] = data.splice(0, sectionSize);
  }
  data3d.sort(function(a,b){return(((a[0][col]<b[0][col])&&a[0][col])?-1:((a[0][col]>b[0][col])?1:0))});
  var sortedData = [];
  for (var k in data3d) {
    for (var l in data3d[k]) {
      sortedData.push(data3d[k][l]);
    }
  }
  sheet.getRange(headerRows+1, 1, sortedData.length, sortedData[0].length).setValues(sortedData);

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about google-apps-script