You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets按首列去重:代码适配改造技术问询

Remove Duplicates Based Only on the First Column in Google Sheets

Got it, I see exactly what you need here. Your existing code is removing duplicate entire rows, but you want to deduplicate solely based on the first column (员工编号)—keeping only the first occurrence of each employee ID, regardless of other column values.

Here's a modified Google Apps Script that does exactly that:

function removeDuplicatesByFirstColumn() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const data = sheet.getDataRange().getValues();
  const seenIds = new Set();
  // We'll iterate from bottom to top to avoid index shifting issues when deleting rows
  for (let i = data.length - 1; i >= 0; i--) {
    const employeeId = data[i][0]; // Get value from first column (index 0)
    if (seenIds.has(employeeId)) {
      // If we've already seen this ID, delete the row
      sheet.deleteRow(i + 1); // Sheet rows are 1-indexed, data is 0-indexed
    } else {
      // Add the ID to our set to track we've seen it
      seenIds.add(employeeId);
    }
  }
  SpreadsheetApp.getUi().alert('Duplicates removed based on first column!');
}

How This Works:

  • Tracking Seen IDs: We use a Set to keep track of every employee ID we've encountered. Sets automatically handle uniqueness, so checking if an ID exists is fast and simple.
  • Reverse Iteration: We loop from the last row to the first. If we deleted rows from top to bottom, the row indexes would shift after each deletion, leading to missed rows or incorrect deletions. Reverse iteration avoids this problem entirely.
  • Targeted Check: Instead of comparing entire rows, we only look at the first column value (data[i][0]) to determine duplicates.

Testing with Your Sample Data:

Your original data:

12345-John-Doe-29
12345-John-Doe-30
12456-Jane-Doe-29
12345-John-Doe-29

After running the script:

  • The first row (12345) is kept
  • Rows 2 and 4 (duplicate 12345 IDs) are deleted
  • Row 3 (12456) is kept intact

This matches exactly what you need—deduplication based only on the employee number, not the entire row.

内容的提问来源于stack exchange,提问作者New_2_Code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:19:07