Google Sheets脚本需求:识别重复项并清空指定列重复值
Google Sheets:保留整行,仅清空重复(Fruits+Item)组合的Item列值
你的需求是识别A列(Fruits)与C列(Item)的组合重复项,仅清空重复项的C列值(保留首次出现的C列内容),但现有代码会直接删除重复行,不符合要求。
原始数据
| Fruits | Price | Item |
|---|---|---|
| Lime | 1 | A |
| Apple | 2 | B |
| Lime | 3 | A |
| Apple | 2 | C |
| Apple | 4 | B |
期望结果
| Fruits | Price | Item |
|---|---|---|
| Lime | 1 | A |
| Apple | 2 | B |
| Lime | 3 | |
| Apple | 2 | C |
| Apple | 4 |
问题分析
现有代码通过筛选不重复整行生成新数据,本质是删除重复行,无法实现「保留行仅清空指定列」的需求。我们需要修改逻辑:遍历所有行,记录已出现的(Fruits+Item)组合,重复时仅清空当前行的Item列。
修正后的代码
function clearDuplicateItems() { const sheet = SpreadsheetApp.getActiveSheet(); const dataRange = sheet.getRange("A2:C"); const data = dataRange.getValues(); const seenCombinations = new Set(); for (let i = 0; i < data.length; i++) { const currentRow = data[i]; // 跳过完全空的行 if (!currentRow[0] && !currentRow[1] && !currentRow[2]) continue; // 用分隔符拼接Fruits和Item,避免不同组合拼接后误判重复 const comboKey = `${currentRow[0]}|${currentRow[2]}`; if (seenCombinations.has(comboKey)) { currentRow[2] = ""; // 清空当前行的Item列 } else { seenCombinations.add(comboKey); } } // 将处理后的数据写回原区域,保留所有行 dataRange.setValues(data); }
代码说明
- 使用
Set存储已出现的(Fruits+Item)组合,判断重复的效率更高 - 用
|作为组合键的分隔符,避免类似"Lime"+"A"和"Lim"+"eA"这种误判为相同组合的情况 - 遍历所有行,仅对重复组合的行清空C列,其余行保持原样
- 最后将处理后的完整数据写回原范围,不会删除任何行
内容的提问来源于stack exchange,提问作者coders_key
相关产品推荐
相关产品推荐

