0

I try to sort an array of values in google script. I got the values with .getRange().getValues(). I want to sort them ascending, but don't know how. I already tried different solutions, but nothing helped. Have maybe someone an idea? Code looks like this at the moment:

Thanks in advance

var values = simsSheet.getRange("A1:NTP1").getValues();
   values.sort(function(a,b){
     return a - b;
   });
Logger.log(values);
4
  • Have you looked into what a and b are? getValues returns Object[Object[]]... (i.e., an array of arrays) Commented Mar 13, 2018 at 13:42
  • What are your values? Commented Mar 13, 2018 at 15:08
  • @AntonDementiev values don't matter yet - OP's comparator function is subtracting an array from an array. Commented Mar 13, 2018 at 16:55
  • 1
    Agreed, but they matter if he wants to compare strings )) Commented Mar 13, 2018 at 16:57

1 Answer 1

0

You will need to decide on which column you want to do the sorting and on what criteria. As mentioned in the comments, your data is an array of arrays so you have to examine data one level further. The most common form of code used for that is as follows :

array.sort(function(x,y){  // tri libellé simplifié
    var xp = x[0]; // in this case on the first column
    var yp = y[0]; // same
    return xp < yp ? -1 : xp > yp ? 1 : 0;
  });

if you want to sort on numeric values for example or on just a part of the data then change the value of x[0] and y[0] to the type of data you want. For example xp = parseInt(x[0],10); would sort on the integer value (without decimals) of the data... a lot of possible variations as you can imagine

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.