Spencer
Spencer

Reputation: 457

Sorted 2D array sorting again on check

I'm using Google Sheets and trying to confirm, using Google Apps Script, that a range is sorted by the last name (second column).
However, there are duplicates in the second column and, when performing the check, the data is re-sorting before the check, flipping the position of rows where the last name matches, at which point the lists don't match.
For instance, the Sheets range is as follows:

First Name Last Name
Frida Acosta
Autumn Acosta
Edgar Andersen
Kayla Andersen
Raphael Andrade
Johnathon Andrews
Danielle Archer

As you can see, rows {1,2} and {3,4} have the same last name. But I've sorted the data on Last Name from Sheets, so this should be correct. However, when I run the code it resorts and flips them, so that it sorts to:

First Name Last Name
Autumn Acosta
Frida Acosta
Kayla Andersen
Edgar Andersen
Raphael Andrade
Johnathon Andrews
Danielle Archer

and now, obviously, they do not match.

How can I check to see if a 2d array is sorted on a single column without having this happen where it attempts to re-sort the array?

function myFunction() {
  const ss = SpreadsheetApp.getActive().getActiveSheet();
  let a1 = ss.getRange(4,1,502,5).getValues();
  let a2 = JSON.stringify(a1);
  a1.sort((a, b) => a[1] > b[1] ? 1 : -1);
  Logger.log(JSON.stringify(a1) == a2);
}

Test Sheet

Upvotes: 0

Views: 79

Answers (1)

Marios
Marios

Reputation: 27348

Solutions:

Basically your approach but without ? 1 : -1:

function myFunction() {
  const ss = SpreadsheetApp.getActive().getActiveSheet();
  let a1 = ss.getRange(4,1,502,5).getValues();
  let a2 = JSON.stringify(a1);
  a1.sort((a, b) => a[1] > b[1] );
  console.log(a1);
}

or:

function myFunction() {
  const ss = SpreadsheetApp.getActive().getActiveSheet();
  let a1 = ss.getRange(4,1,502,5).getValues();
  let a2 = JSON.stringify(a1);
  a1.sort((a, b) => a[1].localeCompare(b[1]));
  console.log(a1);
}

References:

String.prototype.localeCompare()

Upvotes: 1

Related Questions