2

If I understand, if have (I get arr dynamically)

var arr = [7,2,5,1] and I sort it arr.Sort() I get [1,2,5,7]

How do I reverse sort it so I get [7,5,2,1]

function DeleteColsInList() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var Sheet = ss.getSheetByName('ShtName')

  var arr= [7,2,5,1];

 // reverse sort here so I can delete columns in proper order highest to  lowest
  var arrSort =arr.sort()

  for (var i = 0, length = arrSort.length; i < length; i++) {
    Sheet.deleteColumns(arrSort[i]);
   }
  }

UpDated:

function DeleteColsInList() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var Sheet = ss.getSheetByName('ShtName')

  var arr= [7,2,5,1];

 // reverse sort here so I can delete columns in proper order highest to  lowest
  arr.Reverse()

  for (var i = 0, length = arrSort.length; i < length; i++) {
    Sheet.deleteColumns(arr[i] + 1);
   }
  }
3
  • 2
    Can you not sort your array and then arr.reverse()?
    – ale
    Aug 2, 2016 at 20:17
  • I searched but did not find reverse(). Thanks
    – xyz
    Aug 2, 2016 at 20:59
  • I edited the function it now deletes properly with the addition of reverse() also Sheet.deleteColumns(arrSort[i]) needed to be Sheet.deleteColumns(arrSort[i] + 1). I have to say Google sheets sarting at 0 instead of one like I am use to is messing me up!
    – xyz
    Aug 2, 2016 at 21:16

1 Answer 1

5

You can probably do this:

var arrSort =arr.sort();
arrSort.reverse();

I think you can even chain them:

var arrSort = arr.sort().reverse();

Per the comments, even that's more verbose than necessary. You can just do

arr.sort().reverse()

on your original array object.

(h/t to red red wine)

3
  • 2
    The sort method sorts in place, and reverse also operates in place. So, arr.sort().reverse(); is all that's needed; assigning to arrSort just creates another name for the same thing (with arr itself also being sorted and reversed). cc @Tim
    – user79865
    Aug 2, 2016 at 21:21
  • So @AI E. @red red wine, I ended up with, and it appears to work, simply, arrSort = arr.Reverse() no Sort() necessary?
    – xyz
    Aug 2, 2016 at 21:48
  • 1
    @Tim First of all, there is no Reverse method (and no Sort). There are reverse and sort. Second, sort is necessary if you want to sort the array. If you don't want to sort it, it's not necessary. Lastly, as I remarked above, these methods modify the object on which they act. Writing arr.sort() results in arr itself being sorted. There is not need to introduce arrSort into the picture.
    – user79865
    Aug 2, 2016 at 21:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.