在实际开发中,我们经常会遇到需要对数组进行去重的场景。JavaScript 提供了多种方式来实现数组去重,本文将介绍几种常见的方法,并分析它们的优缺点,帮助你在不同场景下选择最合适的方案。
1. 使用 Set 去重
Set 是 ES6 引入的一种数据结构,它只允许存储唯一的值。利用这一特性,可以非常简洁地实现数组去重。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
优点:
- 代码简洁,易于理解。
- 性能较好,时间复杂度为 O(n)。
缺点:
- 无法直接处理对象数组的去重(因为对象是引用类型)。
2. 使用 filter 和 indexOf
通过 filter 方法结合 indexOf,可以过滤掉数组中重复的元素。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
优点:
- 兼容性好,支持 ES5 及更早的环境。
- 适用于简单数据类型的去重。
缺点:
- 性能较差,时间复杂度为 O(n²),因为
indexOf需要遍历数组。
3. 使用 reduce
reduce 方法可以将数组中的元素累积到一个新数组中,同时过滤掉重复的值。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
优点:
- 灵活性高,可以在累积过程中添加额外逻辑。
- 适用于复杂场景。
缺点:
- 代码稍显冗长。
- 性能不如
Set,因为includes需要遍历数组。
4. 使用 forEach 和 includes
通过 forEach 遍历数组,并使用 includes 检查元素是否已经存在于新数组中。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [];
array.forEach(item => {
if (!uniqueArray.includes(item)) {
uniqueArray.push(item);
}
});
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
优点:
- 逻辑清晰,易于理解。
- 适用于简单场景。
缺点:
- 性能较差,时间复杂度为 O(n²)。
5. 使用 Map
Map 是一种键值对数据结构,可以利用它来存储唯一值,然后将 Map 转换回数组。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = Array.from(new Map(array.map(item => [item, item])).map(([key]) => key);
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
优点:
- 性能较好,时间复杂度为 O(n)。
- 适用于需要更复杂操作的场景。
缺点:
- 代码稍显复杂。
6. 使用 lodash 库
如果你不介意使用第三方库,lodash 提供了一个非常方便的 uniq 方法。
const _ = require('lodash');
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = _.uniq(array);
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
优点:
- 代码简洁,功能强大。
- 支持对象数组的去重。
缺点:
- 需要引入第三方库,增加项目体积。
总结
| 方法 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
Set |
简洁、性能好 | 无法直接处理对象数组 | 简单数据类型去重 |
filter + indexOf
|
兼容性好 | 性能较差 | 兼容性要求高的场景 |
reduce |
灵活性高 | 代码稍显冗长 | 复杂逻辑场景 |
forEach + includes
|
逻辑清晰 | 性能较差 | 简单场景 |
Map |
性能较好 | 代码稍显复杂 | 需要复杂操作的场景 |
lodash |
功能强大、简洁 | 需要引入第三方库 | 项目中已使用 lodash 的场景 |
在实际开发中,推荐优先使用 Set,因为它简洁且性能优异。如果需要兼容性更好的方案,可以选择 filter 和 indexOf。对于复杂场景,reduce 和 Map 是不错的选择。如果项目中已经使用了 lodash,可以直接使用它的 uniq 方法。
希望本文能帮助你更好地理解和掌握 JavaScript 数组去重的多种实现方式!如果你有其他更好的方法,欢迎在评论区分享!








网友评论