使用 Set
(最简单、最常用)
Set
是 JavaScript 内置的数据结构,它会自动去重。
function uniqueArray(arr) {
return [...new Set(arr)];
}
const arr = [1, 2, 2, 3, 4, 4, 5];
console.log(uniqueArray(arr)); // 输出: [1, 2, 3, 4, 5]
优点:性能好,代码简洁。
缺点:不能去除对象数组中的重复项。
使用 filter()
+ indexOf()
适用于简单数组,通过 filter
仅保留第一次出现的元素。
function uniqueArray(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
console.log(uniqueArray([1, 2, 2, 3, 4, 4, 5])); // 输出: [1, 2, 3, 4, 5]
优点:易懂,可用在 ES5。
缺点:性能不如 Set
,适用于小数组。
使用 reduce()
利用 reduce
进行去重。
function uniqueArray(arr) {
return arr.reduce((acc, cur) => {
if (!acc.includes(cur)) acc.push(cur);
return acc;
}, []);
}
console.log(uniqueArray([1, 2, 2, 3, 4, 4, 5])); // 输出: [1, 2, 3, 4, 5]
优点:适用于复杂数组(如对象数组)。
缺点:性能较低。
使用 Map
对象
Map
对象也是一种类似于 Set
的数据结构,但是它可以存储键值对,可以通过它来去重。
代码示例:
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Map(arr.map(item => [item, item])).values()];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
解释:
arr.map(item => [item, item])
把每个元素转换成一个键值对的数组。new Map()
会自动去除重复的键。values()
返回Map
中所有键值对的值部分,再通过扩展运算符[...]
转换为数组
排序 + 过滤(适用于已排序数组)
如果数组是有序的,可以先排序再去重。
function uniqueSortedArray(arr) {
return arr.sort().filter((item, index, array) => item !== array[index - 1]);
}
console.log(uniqueSortedArray([5, 3, 3, 1, 2, 2, 4, 4]));
// 输出: [1, 2, 3, 4, 5]
优点:适用于已排序数组。
缺点:需要额外的 sort()
操作。
总结
方法 | 适用范围 | 执行逻辑 | 复杂度 |
---|---|---|---|
Set | 基本类型 | 自动去重 | O(n) |
filter() + indexOf() | 基本类型 | 逐个查找是否首次出现 | O(n²) |
reduce() + includes() | 基本类型 | 逐个查找是否已加入 | O(n²) |
Map | 对象数组 | 以 id 作为 Map key 存储 | O(n) |
如果你需要 最简单、性能最好的 方法,建议使用 Set()
。
如果是 去重对象数组,建议使用 Map()
或 对象键值法。