问题
I have a column with a set of numbers I am prepping for a query. Some of these numbers have leading zeros and I will need to keep it on the list with leading zeros and without leading zeros.
What I have done so far is to create a column of values with leading and without leading zeros. Here is an example of the array when I getValues on the column.
[[1],[2],[001],[002],[1],[2]]
The end result should be...
[[1],[2],[001],[002]]
The last two were dropped because they were duplicates and I only need it in the array once.
Here is what I am trying but I am having issues:
var array = sh.getRange(1,sh.getLastColumn(),sh.getLastRow(),1).getValues();
var uniqueArray = removeDuplicates(array)
function removeDuplicates(myArray){
var newArray = [];
myArray.forEach(function(x){
if(newArray.indexOf(x[0]) === -1){
newArray.push(x[0]);
}
});
}
Error: The array comes back as null and then when I try to get uniqueArray.length it will give me TypeError: Cannot read property 'length' of undefined
I've also tried:
var uniqueArray = Array.from(new Set(array));
This seems like it would be less taxing and I like it but it returns all values. It doesn't drop the duplicates.
What am I doing wrong and what is the best approach? How can I fix this?
回答1:
Using Sets:
const removeDuplicates = arr2d => [...new Set(arr2d.flat())].map(e => [e]);
console.info(removeDuplicates([[1],[2],[001],[002],[1],[2]]))
Use getDisplayValues to get Strings
回答2:
Try this:
function removeDups(mA){
//Logger.log('vA:',mA);
let s=new Set();
mA.forEach(function(a){
a.forEach(function(e) {
s.add(e);//add elements to a set
});
});
//Logger.log('set: %s',s.keys());
const oA=[...s];//expand the set back to a unique array
//Logger.log('oA: %s',oA);
return oA;
}
Note: this requires the new v8 engine
Also I noticed that the logger output is reported much more quickly to the same page as you get when you view executions.
JavaScript Set
Set.add()
来源:https://stackoverflow.com/questions/60764597/gas-issue-with-removing-duplicates-from-array