如何使用javascript从Google电子表格中的列的所有值中获取排序的唯一值

时间:2017-09-04 09:39:59

标签: javascript arrays google-apps-script google-spreadsheet-api

我需要帮助才能获得特定列(B列)的唯一排序值列表。

这是我的尝试(它没有用),你能帮我找到错误吗?

我无法以[对象]格式获得正确的范围...

function onlyUnique(value, index, self) { 
return self.indexOf(value) === index;
}  

function UniqueRange()  {
var s = SpreadsheetApp.getActiveSpreadsheet();
var sht = s.getSheetByName('Prova')
var drng = sht.getDataRange();
var rng = sht.getRange(2,2, drng.getLastRow()-1,1);
var rngA = rng.getValues();
var shtout = s.getSheetByName('Nuovo');
var rngout = shtout.getRange(2,1,rngA.length,1)
var rngB = rngout.setValues(rngA);
var i = 0; i < rngA.length; i++
var rngB = rngB[i];  
var unique = rngB.filter( onlyUnique ); 
}

Bellian的解决方案:

function onlyUnique(value, index, self) { 
return self.indexOf(value) === index;
} 
function uniquevalues(){
var s = SpreadsheetApp.getActiveSpreadsheet();  
var sht = s.getSheetByName('Prova')  
var drng = sht.getDataRange();
var rng = sht.getRange(2,2, drng.getLastRow()-1,1);  //range that contain all values
var rngA = rng.getValues();
var unique = [];
 for(var i = 0; i < rngA.length; i++) {
var unique = unique.concat(rngA[i+1]);
} 
unique = unique.filter(onlyUnique);
Logger.log(unique)
}

1 个答案:

答案 0 :(得分:0)

function getUniqueSortedArray(sheetname,column,datastartrow) 
{
  if(sheetname && column && datastartrow)
  {  
    var ss=SpreadsheetApp.getActive();
    var cntSh=ss.getSheetByName(sheetname);
    var cntRg=cntSh.getDataRange().sort({column:column,ascending:true});
    var vA=cntRg.getValues();
    var uiA=[];
    for(var i=datastartrow-1;i<vA.length;i++)
    {
      if(uiA.indexOf(vA[i][column-1])==-1)
      {
        uiA.push(vA[i][column-1]);
      }
    }
    return uiA;
  }
  else
  {
    return 'Invalid Inputs';
  }
}

这是我对你的代码的修改。

function UniqueSortedRange()  
{
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sh=ss.getSheetByName('Prova')
  var rg=sh.getDataRange().sort({column:2,ascending:true});
  var vA=rg.getValues();
  var sh0=ss.getSheetByName('Nuovo');
  var luneeko=[];
  for(var i=1;i<vA.length;i++)
  {
    if(luneeko.indexOf(vA[i][1])==-1)
    {
      luneeko.push(vA[i][1]);
    }
  }
  return luneeko;
}