empirebattles
empirebattles

Reputation: 3

Google Scripts 2D Array sorting by value

I have a 2d array that I am attempting to sort.

The array is typically accessed with this structure: array[r][c].

I want to re-order the values of array, so that each [r] value is sorted by the 4th c value.

Looking online, I've seen a few sorting scripts that seem to work for other structured arrays, but I'm wondering if i'm missing something stupid.

The array is structured so that for each 'r' value in array, there is a list of values, depending on what 'c' value you put in (eg: if you do array[0][2] that will be the first entry's address, and array[0][10] is the first entry's phone number).

I want to be able to sort based off of c values 4 and... 10 (for example). (ideally, I'd sort by multiple columns, such as sort by last name first, then by first name--but i'll settle for one sort for now hahaha )

I'm not certain if any of the default sort functions would work for me, or if i need to write out a manual sort function (which i'm hoping i do not have to do as that would be fairly inefficient).

Thanks for any pointers

Upvotes: 0

Views: 1002

Answers (1)

TheMaster
TheMaster

Reputation: 50797

You'll need to write your own compare function.

Snippet:

const COLTOSORT = 2;
function compare(row1, row2) {
  return row1[COLTOSORT] < row2[COLTOSORT]
    ? -1
    : row1[COLTOSORT] > row2[COLTOSORT]
      ? 1
      : 0;
}
array.sort(compare);

References:

Upvotes: 1

Related Questions