目前还不清楚为什么要在此处使用脚本,因为可以使用普通的电子表格公式按要求过滤范围,如下所示:
=arrayformula(
iferror(
vlookup(
unique(A2:A),
sort(A2:D, row(A2:D), false),
column(A2:D),
false
)
)
)
要将原始数据替换为唯一结果,请使用 ControlC 复制和 ControlShiftV 仅粘贴值。在 Mac 上,使用 ⌘C 和 ⌘ShiftV。
这个问题指定了 Apps 脚本,所以这里有一个自定义函数来做同样的事情,还有一个简单的函数使用它来过滤电子表格中的硬编码范围。
/**
* Removes duplicates in 'Sheet1!A2:D'.
* Keeps each last row where a key appears.
* Other rows are cleared.
*/
function removePriorDuplicates() {
const range = SpreadsheetApp.getActive().getRange('Sheet1!A2:D');
const uniques = getLastUniques(range.getValues(), 0);
range
.clearContent()
.offset(0, 0, uniques.length, uniques[0].length)
.setValues(uniques);
}
/**
* Gets exactly one row per each unique key in a key column.
* Keeps each last row where a key appears.
* Other rows are filtered out.
*
* @param {Object[][]} array2D The array to filter.
* @param {Number} columnIndex The zero-indexed column number where keys appear.
* @return {Object[][]} A 2D array where there is just one copy of each key.
* @customfunction
*/
function getLastUniques(array2D, columnIndex) {
// version 1.0, written by --Hyde, 16 September 2021
// - see https://stackoverflow.com/a/69204946/13045193
const keys = array2D.map(row => row[columnIndex]);
return array2D.filter((row, index) => keys.lastIndexOf(row[columnIndex]) === index);
}