陣列去重是前端高頻考題與實務需求。本文系統整理三種經典演算法,從原理、代碼、效能、優缺點到適用場景全方位解析。
Array.prototype.unique1 = function () {
const res = [this[0]];
for (let i = 1; i < this.length; i++) {
let repeat = false;
for (let j = 0; j < res.length; j++) {
if (this[i] === res[j]) { repeat = true; break; }
}
if (!repeat) res.push(this[i]);
}
return res;
};
Array.prototype.unique2 = function () {
const sorted = [...this].sort(); // 複本排序,不汙染原陣列
const res = [sorted[0]];
for (let i = 1; i < sorted.length; i++) {
if (sorted[i] !== res[res.length - 1]) res.push(sorted[i]);
}
return res;
};
Array.prototype.unique3 = function () {
const res = [];
const seen = {}; // 或 new Set()
for (let i = 0; i < this.length; i++) {
const val = this[i];
if (!seen[val]) { // 注意:鍵會被轉字串,1 與 "1" 會衝突
res.push(val);
seen[val] = 1;
}
}
return res;
};
Array.prototype.unique3Typed = function () {
const res = [];
const seen = new Map(); // Map 鍵保持原型別
for (const val of this) {
const key = typeof val + ":" + val; // 簡易鍵
if (!seen.has(key)) {
res.push(val);
seen.set(key, true);
}
}
return res;
};
const unique = arr => [...new Set(arr)];
| 方法 | 時間複雜度 | 保持順序 | 型別區分 | 物件去重 | 推薦指數 |
|---|---|---|---|---|---|
| 雙層迴圈 | O(n²) | ✅ | ✅ | 參考比較 | ⭐ (教學用) |
| 排序比鄰 | O(n log n) | ❌ | ❌ (1=="1") | ❌ | ⭐⭐ (舊環境) |
| Object/Map | O(n) | ✅ | ✅ (加前綴) | 參考比較 | ⭐⭐⭐⭐ |
| Set | O(n) | ✅ | ✅ (SameValueZero) | 參考比較 | ⭐⭐⭐⭐⭐ (現代首選) |
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;
});
}
// ⚠️ 局限:無法處理函式、循環引用、屬性順序不同但內容相同
[...new Set(arr)]`,簡潔高效。