[英]How to get the unique items out of a list in Google Apps Script?
I have this code snippet:我有这个代码片段:
function getTimeFrames(){
var ss = SpreadsheetApp.getActive();
var cell = ss.getRange("C1").getValue();
Logger.log(cell);
var s = ss.getSheetByName(cell).getRange("M2:M");
var unique = new Set(s.getValues());
unique.forEach(x => Logger.log(x))
}
This code would be called from a Google Sheets spreadsheet which serves as an UI, where the C1 cell would be a name of a sheet used for storing data.将从用作 UI 的 Google Sheets 电子表格调用此代码,其中 C1 单元格将是用于存储数据的工作表的名称。 In that sheet I have a column (M) that I need to get the unique values out of in order to store in a drop-down in the UI sheet.在那张工作表中,我有一个列 (M),我需要从中获取唯一值,以便存储在 UI 工作表的下拉列表中。
The problem I have is that I can't get the unique values part working at all.我遇到的问题是我根本无法使唯一值部分起作用。 Throughout my experimentation, I would either get a list of all the values of column M or no Logging output at all.在整个实验过程中,我要么得到列 M 的所有值的列表,要么根本没有记录 output。
Any help is greatly appreciated!任何帮助是极大的赞赏!
Try尝试
function getTimeFrames(){
var ss = SpreadsheetApp.getActive();
var cell = ss.getRange("C1").getValue();
Logger.log(cell);
var unique = ss.getSheetByName(cell).getRange("M2:M").getValues().flat().filter(onlyUnique)
console.log(unique)
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
This was really a tough job before ES6 .在ES6之前,这确实是一项艰巨的工作。 But now, with a combination of filter() and indexOf() you can easily pull it off.但是现在,结合使用filter()和indexOf() ,您可以轻松实现它。
For Example:例如:
var List = ['One','Two','Two','One','One','Two','One','Three']
const uniqueList = (value,index,self) =>
{return self.indexOf(value) ===index;}
var finalUniqueList =List.filter(unique);
Try spreading the unique values into an array:尝试将唯一值散布到一个数组中:
function getTimeFrames() {
const sheet = SpreadsheetApp.getActive()
const cell = sheet.getRange(`C1`).getValue()
const values = sheet.getSheetByName(cell)
.getRange(`M2:M`)
.getValues()
.filter(String)
.flat()
const unique = [...new Set(values)]
Logger.log(unique)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.