SpreadsheetApp how to return unique values from an array

 ̄綄美尐妖づ 提交于 2021-01-01 06:37:46

问题


Here is the function I made. The var myArray is a list of names. I'm not able to get only unique values from this array and set it to another sheet. I just want the names once.

function array() {          
      var app = SpreadsheetApp;
      var ss = app.getActiveSpreadsheet().getSheetByName("test");
      var destinationSheet = app.getActiveSpreadsheet().getSheetByName("test2");

      var myArray = ss.getRange(2,1,30).getValues();

      destinationSheet.getRange(2, 1, 30).setValues(myArray);   
}

Can someone help me to filter this array?


回答1:


Javascript Arrays have the method from using which you can create an array form a set of values, be it String, Map or Set.

Add this after the definition of myArray in your code

myArray = Array.from(new Set(myArray));

You can read more about it here.

OR

You can use a simple forEach loop to filter unique values.

Assuming your array contains names only, and getValues returns 2-D arrays, so, your array looks something like - [['name1', 'name2', 'name3']].

var newArray = [];
myArray.forEach(function(x){
    if(newArray.indexOf(x[0]) === -1){
        newArray.push(x[0]);
    }                   
});



回答2:


Here's an alternative approach (for Google Script)

function myArray() {
var ss, s, a;
ss = SpreadsheetApp.getActive();
s = ss.getSheetByName("test").getRange(2, 1, 30).getValues();
a = [];
a.push(s[0]);
for (var n = 1; n < s.length; n++) {
    if (a.join().indexOf(s[n].join()) == -1) {
        a.push(s[n])
    };
}
ss.getSheetByName("test2").getRange(2, 1, a.length, a[0].length).setValues(a);
}


来源:https://stackoverflow.com/questions/47625755/spreadsheetapp-how-to-return-unique-values-from-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!