Guest User

google apps script

a guest
Jan 20th, 2025
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. function customSortTwoColumns() {
  2. const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  3. const range = sheet.getDataRange();
  4. const values = range.getValues();
  5.  
  6. // separate header row (first row)
  7. const header = values.shift(); // remove first row from sorting
  8.  
  9. // sort remaining rows
  10. values.sort((a, b) => {
  11. // first column: sort lexicographically
  12. const col1Comparison = a[0].toString().localeCompare(b[0].toString());
  13. if (col1Comparison !== 0) return col1Comparison;
  14.  
  15. // second column: sort numerically (ignoring text after space)
  16. const numA = parseFloat(a[1].toString().split(" ")[0]) || 0;
  17. const numB = parseFloat(b[1].toString().split(" ")[0]) || 0;
  18. return numA - numB;
  19. });
  20.  
  21. // add the header row back and write the sorted data to the sheet
  22. values.unshift(header); // add the header row back to the top
  23. range.setValues(values);
  24. }
Advertisement
Add Comment
Please, Sign In to add comment