我正在看这里的帖子,它与我为项目所做的工作非常接近。我将如何更改它以使其如下所示工作:
我在“测试表”的A列至P列中有数据。 P列提供“ DisputeStatus”。该状态可以是以下三种状态之一:NULL,PENDING或APPROVED。每天都会将新数据添加到行的底部。仅当每天向底部添加新数据并且上面先前记录的订单项的“ DisputeStatus”已更改时,才创建重复项。因此,我现在将在A列到O列中有两行数据完全相同,但是在P列(“ DisputeStatus”)中,一行将显示PENDING,另一行则显示APPROVED。我想查找重复项,然后只删除状态为“旧优先级”的重复项,并保留状态为“新优先级”的重复行。
例如:
以下状态优先级集是P列中具有不同“ DisputeStatus”的可能重复行:
NULL (old)(delete)
PENDING (new)(keep)
PENDING (old)(delete)
APPROVED (new)(keep)
PENDING (old)(delete)
DENIED (new)(keep)
function removeDuplicates()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test Sheet");
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
var indexOfStatusColumn = 16;
var newData = [];
data.forEach(function (row, rowI){
var isDuplicate = false
if (newData.length)
newData.forEach(function (dup, dupI)
{
if (dup[3] == row[3])
{
if (row[indexOfStatusColumn] == "APPROVED" && dup[indexOfStatusColumn] != "APPROVED")
newData[dupI][indexOfStatusColumn] = "APPROVED";
isDuplicate = true;
return (false);
}
})
if (!isDuplicate)
newData.push(row);
});
dataRange = sheet.getRange(2, 1, dataRange.getLastRow() - 1, dataRange.getLastColumn());
dataRange.clearContent();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
答案 0 :(得分:0)
这是完整的工作代码,可按照您的说明删除重复项。它将使要删除的行位置组成一个数组(满足条件的行),并且在循环之后将删除那些重复的行。
function removeDuplicates() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test Sheet");
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
data.shift();
var indexOfStatusColumn = 16;
var rowsDelete = [];
data.forEach(function (row, rowI){
data.forEach(function (row2, row2I) {
if (row2[3] == row[3]) {
if ((row[indexOfStatusColumn] == "APPROVED" && row2[indexOfStatusColumn] != "APPROVED") || (row[indexOfStatusColumn] == "PENDING" && row2[indexOfStatusColumn] == "NULL")) {
var rowNum = Number(row2I + 2);
if (rowsDelete.indexOf(rowNum) == -1) {
rowsDelete.push(rowNum);
}
}
}
})
});
rowsDelete.sort(function(a, b){return b-a}); // Sort the numbers in the array in descending order
rowsDelete.forEach(function (rowNum, rowI){
sheet.deleteRow(rowNum); //Delete rows
})
}