对表单项的选择进行排序

Sort choices of a form item

我有一个脚本可以在提交时向表单问题添加一个选项。添加后,它显示在底部。如何对选项列表进行排序?

使用getChoices(*) to retrieve an array of all the existing choices you already have, push your new choice in this array, sort this array and finally add the sorted array of choices using setChoices([])(**).

根据您的评论,我进行了更深入的研究,找到了一种可行的方法。下面是一个演示测试代码,其中我将一个项目添加到列表中并按字母顺序对项目进行排序。 本例中列表题为第四题,请根据自己的情况进行调整。 (代码中的注释,一步一步)

function sortList(){
  var f = FormApp.getActiveForm();
  var list = f.getItems()[3]; // this was my test form configuration
  var choices = list.asListItem().getChoices();
  var newChoice = list.asListItem().createChoice('0000 option');// an example that should come first in the list of choices
  var sortedChoices = [];
  sortedChoices.push([newChoice.getValue(),newChoice]);// add to the array, order doesn't matter
  for(var n in choices){
    Logger.log(choices[n].getValue());
    sortedChoices.push([choices[n].getValue(),choices[n]]);// add all existing items    
  }
  Logger.log(JSON.stringify(sortedChoices));// see the unsorted content
  sortedChoices.sort(function(x,y){
  var xp = x[0];
  var yp = y[0];
  return xp == yp ? 0 : xp > yp ? 1 : -1;//  sort on choice value only
});
  var resultChoices = [];
  for(var n in sortedChoices){
    resultChoices.push(sortedChoices[n][1]);// create a new array with only useful objects    
  }  
  Logger.log(JSON.stringify(resultChoices));// check in logger
  list.asListItem().setChoices(resultChoices);// update the form
}

对 Serge 发布的代码进行了轻微修改,以简化和修复排序函数,以允许按值直接对选择数组进行排序,而无需创建值数组、排序和重新创建排序数组。这也维护了导航数据。

function sortList(){
  var f = FormApp.getActiveForm();
  var list = f.getItems()[3]; // this was my test form configuration
  var choices = list.asListItem().getChoices();
  var newChoice = list.asListItem().createChoice('0000 option');// an example that should come first in the list of choices
  choices.push(newChoice);

  choices.sort(function(x,y){
    var xp = x.getValue();
    var yp = y.getValue();
  return xp == yp ? 0 : xp > yp ? 1 : -1;//  sort on choice value only
});

  list.asListItem().setChoices(choices);// update the form
}