I have a script that I have been using for some time, but I recently had a bug on the data sorter and since then I have been unable to fix the problem.
I transpose arrays because they are normally horizontal.
I have a list of data and values from staff rounds. There are missing values depending on the round. I add the missing names with a value of " ", then sort them so I can paste the data into a database. But for a few days now, the sorting part hasn't been working properly.
- First row: Data name
- Second row: Data value
- Third row: Data name in the desired order
name : | A | B | E | D | C |
---|---|---|---|---|---|
value : | 10 | 2 | 35 | 4 | 12 |
order : | A | B | C | D | E |
the result it did before, with empty name at the end:
name : | A | B | C | D | E | "" |
---|---|---|---|---|---|---|
value : | 10 | 2 | 12 | 4 | 35 | "" |
the result it give now:
name : | A | D | C | "" | B | E |
---|---|---|---|---|---|---|
value : | 10 | 4 | 12 | "" | 2 | 35 |
function test() {
var objects = spreadsheet.getSheetByName("Feuille 121").getRange("A1:GG2").getValues()
var order = spreadsheet.getSheetByName("Feuille 121").getRange("A3:GG3").getValues().flat()
objects = Object.keys(objects[0]).map(function(c) {
return objects.map(function(r) {
return r[c];
});
});
order = Object.keys(order[0]).map(function(c) {
return order.map(function(r) {
return r[c];
});
});
// organise dans l'ordre des paramètre
let orderIndex = {}
order.forEach((value, index) => orderIndex[value] = index);
// Sort
objects.sort((a, b) => orderIndex[a[0]] - orderIndex[b[0]]);
var length = objects.length
objects = Object.keys(objects[0]).map(function(c) {
return objects.map(function(r) {
return r[c];
});
});
console.log(objects)
spreadsheet.getSheetByName("Feuille 121").getRange(1, 1, 2, length).setValues(objects)
}
objects
you are trying to sort, doesn't make sense since you said that you are trying to sort 2D array, check some sort of a Primary key value to be compared on the some sort of the template you have on another row, however theobject
array you created doesn't need the extra step which makes your expected result more confusing. I do think that providing more information about the data and expected results, the exact bug can help the community understand you better.