0
votes

I've been working with GAS for little while, but don't have a strong Javascript background, and am running into a problem sorting my sheets alphabetically while ignoring case. I did some hunting and put together this method based on other public answers in SO and a few other sources. Say my sheets are named "Sheet1", "my Other Sheet", "The 3rd Sheet", "another sheet", "By gosh another one?". I would want my sheets to be ordered: "another sheet","By gosh another one?","my Other Sheet","Sheet1","The 3rd Sheet"

var spsheet = SpreadsheetApp.getActive()
var sheets = spsheet.getSheets()
var names =[]
sheets.forEach(function(item){
  names.push(item.getName())
})
var sortednames = names.sort(function(a,b){
   return ((a.toUpperCase() > b.toUpperCase()) ? 1:-1)

  {)

Am I misunderstanding? I thought that the toUpperCase() calls would temporarily change the case of each name only for the purposes of sorting, and then sort my sheet names alphabetically, before returning a sorted list of my sheets that ignores case. However, this the actual output is:[By gosh another one?, Sheet1, The 3rd Sheet, another sheet, my Other Sheet]

It seems that I am first sorting the uppercased sheets alphabetically and then following that sorting with the lowercased sort. Am I on the right track here? Or have I fully misunderstood something?

1
I think that when names is ["Sheet1", "my Other Sheet", "The 3rd Sheet", "another sheet", "By gosh another one?"], names.sort(function(a,b){return a.toUpperCase() > b.toUpperCase() ? 1 : -1}) returns ["another sheet","By gosh another one?","my Other Sheet","Sheet1","The 3rd Sheet"], while names.sort(function(a,b){return a > b ? 1 : -1}) returns [By gosh another one?, Sheet1, The 3rd Sheet, another sheet, my Other Sheet]. How about this? By the way, {) is })?Tanaike
Hello! I have tried the code that you are using, however, the results obtained are the ones expected (proper sorting - see imgur.com/a/hKaC7AG). Could you try logging the sortednames variables right after creating it and see if the results are the expected? Cheerscarlesgg97

1 Answers

0
votes

Try this:

function sortSheetsByNameCaseInsensitive() {
  var ss=SpreadsheetApp.getActive();
  var shts=ss.getSheets();
  var nameA=shts.map(function(sh,i){return sh.getName()});
  var nameB=shts.map(function(sh,i){return sh.getName().toLowerCase()});
  var nameC=nameB.slice();
  nameC.sort();
  for(var i=0;i<nameC.length;i++) {
    var sh=ss.getSheetByName(nameC[i]);
    var idx=nameB.indexOf(nameC[i]);
    sh.setName(nameA[idx]);
    Sheets.Spreadsheets.batchUpdate({requests:[{"updateSheetProperties":{"properties":{"sheetId":sh.getSheetId(),"index":i+1},"fields":"index"}}]}, ss.getId());
  }
}