Array.prototype.distinct = function () {
const a = [], b = {}; // b 作為 Hash Set
for (const prop in this) {
const val = this[prop];
if (val === a[prop]) continue; // 原型鏈保護(舊寫法)
if (b[val] !== 1) {
a.push(val);
b[val] = 1;
}
}
return a;
};
⚠️ **問題**:
Array.prototype.distinct = function () {
const a = [], b = {}, c = [], d = {};
for (const prop in this) {
const val = this[prop];
if (val === a[prop]) continue;
if (b[val] !== 1) { a.push(val); b[val] = 1; }
else { c.push(val); d[val] = 1; }
}
return c.distinct1(); // 再去重一次
};
同樣存在上述所有問題,且邏輯繞彎。
const unique = arr => [...new Set(arr)];
// 或保持順序的 filter
const uniqueOrdered = arr => arr.filter((v, i, a) => a.indexOf(v) === i);
function uniqueTyped(arr) {
const seen = new Map();
return arr.filter(v => {
const key = typeof v + "#" + v;
return seen.has(key) ? false : seen.set(key, true);
});
}
function getDuplicates(arr) {
const seen = new Map(); // val -> count
const dup = [];
for (const v of arr) {
const cnt = (seen.get(v) || 0) + 1;
seen.set(v, cnt);
if (cnt === 2) dup.push(v); // 只有第二次出現才加入
}
return dup;
}
// [1,2,3,2,1,4] → [2, 1]
function getAllDuplicates(arr) {
const counts = new Map();
for (const v of arr) counts.set(v, (counts.get(v) || 0) + 1);
return arr.filter(v => counts.get(v) > 1);
}
// [1,2,2,3,3,3] → [2,2,3,3,3]
function uniqueDeep(arr) {
const seen = new Set();
return arr.filter(item => {
const key = JSON.stringify(item); // 簡易序列化
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
// ⚠️ 局限:屬性順序、函式、循環引用、Symbol 會失效
| 方法 | 耗時 | 記憶體 | 適用 |
|---|---|---|---|
| Set | ~8ms | 低 | 基本型別、物件參考 |
| Map + 型別鍵 | ~15ms | 低 | 需區分 1/"1" |
| filter + indexOf | ~1200ms | 低 | 小陣列、無 ES6 |
| 原型 for-in + Object | ~2000ms | 高 | 不推薦 |