@IT·互联网

JavaScript 数组去重的多种实现方式

2025-03-12  本文已影响0人  vvilkin

在实际开发中,我们经常会遇到需要对数组进行去重的场景。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]

优点:

缺点:


2. 使用 filterindexOf

通过 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]

优点:

缺点:


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]

优点:

缺点:


4. 使用 forEachincludes

通过 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]

优点:

缺点:


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]

优点:

缺点:


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,因为它简洁且性能优异。如果需要兼容性更好的方案,可以选择 filterindexOf。对于复杂场景,reduceMap 是不错的选择。如果项目中已经使用了 lodash,可以直接使用它的 uniq 方法。

希望本文能帮助你更好地理解和掌握 JavaScript 数组去重的多种实现方式!如果你有其他更好的方法,欢迎在评论区分享!

上一篇 下一篇

猜你喜欢

热点阅读