因为“独特”并不总是很容易描述,所以我经常使用一种模式,它实际上是 Serge 使用 ES5 数组映射/过滤函数的正确答案的变体。
经过编辑的版本:
function hash(arr) {
// in this case the hash method is the same as Serge's Array.join() method,
but could be customised to suit whatever condition you need to generate
bespoke comparators such as where `1 + 3` should match `2 + 2`, or where
particular columns in the array can be omitted
return arr.join();
}
function myFunction() {
var source = [['Option 10', 2], ['Option 10', 2], ['Option 9', 1], ['Option 7', 1]];
var hash = source.map(
function (row) {
return hash(row);
}
);
source = source.filter(
function (filterRow, i) {
return hash.slice(0, i).indexOf(hash(filterRow)) < 0;
}
);
Logger.log(source);
}
我仅将其包括在内,因为有时您的比较可能需要稍微调整一下。在您的示例中,这并不重要,这就是 Serge 正确的原因,但我分享了一个潜在的扩展,以供思考何时需要“调整”独特性