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?
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"]
, whilenames.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})
? – Tanaikesortednames
variables right after creating it and see if the results are the expected? Cheers – carlesgg97