谷歌应用程序脚本数组从顶部删除重复的值 [英] google app script array delete duplicate value from top
问题描述
我有这个工作代码,它通过比较B列中的值来删除重复项.如果第2行和第3行在B列中具有相同的值,则删除第3行.
I've got this working code that removes duplicates by comparing values in column B. If row 2 and 3 have the same values in column B then row 3 is deleted.
function removeDuplicates() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var newData = new Array();
for(i in data){
var row = data[i];
var duplicate = false;
for(j in newData){
if(row[1] == newData[j][1]){
duplicate = true;
}
}
if(!duplicate){
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
如何更改此代码以通过编辑此代码来构建阵列,以便删除第2行而不是删除第3行?
How can I change this code to build the array from edit this so that instead of row 3 being deleted, row 2 is deleted?
推荐答案
我认为这可以做到.
function removeDuplicates() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var rg=sh.getDataRange();
var row=rg.getRow();
var col=rg.getColumn();
var vA=rg.getValues();
var nA=[];
var duplicate=true;
for(var i=0;i<vA.length;i++)
{
duplicate=false;
for(var j=0;j<nA.length;j++)
{
if(vA[i][1]==nA[j][1])
{
duplicate=true;
nA[j]=vA[i];
}
}
if(!duplicate)
{
nA.push(vA[i]);
}
}
rg.clearContent();
sh.getRange(row, col, nA.length, nA[0].length).setValues(nA);
}
外部循环遍历活动工作表的所有行,并且每次循环都将重复项设置为false.内循环搜索nA []来查找columnB匹配项,如果找到匹配的列,则将该副本设置为true.如果重复为true,则不会将其添加到nA []中.第一次通过nA.length为0,因此内部循环不执行任何重复操作都为false,因此该元素被添加到nA []中.它会一直这样做,直到没有更多的行并且nA中的行成为唯一行为止.那就是我第一次做的时候的运行方式.但是由于您想保留最后一个而不是第一个重复,因此我添加了nA[j]=vA[i];
,它将当前元素替换为当前匹配项.
The outer loop is iterating through all of the rows of the active sheet and each time through it sets duplicate to false. The inner loop searches through nA[] looking for columnB matches if it finds one it sets duplicate to true. If duplicate is true then it doesn't get added to nA[]. The first time through nA.length is 0 so the inner loop doesn't do anything duplicate is false and so that element gets added to nA[]. It keeps doing this until there are no more rows and the rows that are in nA become the unique row. That's the way it use to run when I first did it. But since you wanted to keep the last duplicate instead of the first then I added nA[j]=vA[i];
which replaces the current element with the current match.
只需设置一些虚假数据并进行处理,您将开始了解其工作原理.
Just setup some fake data and play with it and you'll start to see how it works.
这篇关于谷歌应用程序脚本数组从顶部删除重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!