JS 数组去重 — 各类场景适合方法大全

14 篇文章 0 订阅

JS 数组去重 — 各类场景适合方法大全

本文介绍各种场景 JS 去重 方法使用 性能最好、用的最多、场景大全

在这里插入图片描述

在这里插入图片描述

一、基础篇:简单直观的去重方法

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. 利用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]

3. reduce方法的应用

reduce方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。通过累积器acc和当前值current的比较,我们可以实现去重逻辑。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, current) => {
  if (!acc.includes(current)) acc.push(current);
  return acc;
}, []);
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]

二、进阶篇:性能与效率的优化

4. 优化后的Set方法

对于大数据集,直接使用Set进行去重通常是最优选择。Set内部使用了哈希表来存储值,因此查找和插入的时间复杂度接近O(1),性能表现优异。

// 生成大量重复数据
const array = Array.from({ length: 1000000 }, (_, i) => i % 1000);
const uniqueArray = [...new Set(array)];
console.log(uniqueArray.length); // 输出: 1000

5. 对象键值对的巧妙利用

对象的键值对具有唯一性,这一特性可以被用来实现数据去重。通过将数组元素作为对象的键,我们可以快速去重并保留元素的顺序。

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueObj = {};
array.forEach(item => uniqueObj[item] = true);
const uniqueArray = Object.keys(uniqueObj).map(Number); // 转换键回数字类型
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]

三、实战篇:常用与特殊需求的解决方案

6. 结合Map和Set的强大功能

Map能够保持插入顺序,而Set则确保值的唯一性。通过将两者结合,我们可以实现既保持顺序又去重的目标。

const array = [1, 2, 2, 3, 4, 4, 5, {a: 1}, {a: 1}];
const uniqueArray = Array.from(new Map(array.map(item => [JSON.stringify(item), item])).values());
console.log(uniqueArray); // 输出包含唯一对象的数组

7. Lodash库的uniq方法

Lodash是一个一致性、模块化、高性能的JavaScript实用工具库。它提供了丰富的API,其中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]

8. 支持终止条件的去重方法

在某些特定场景下,我们可能需要在满足特定条件时终止去重操作。这时,我们可以使用for循环结合break语句来实现。

const array = [1, 2, 2, 3, 4, 4, 5, 'stop', 6];
const uniqueArray = [];
const stopValue = 'stop';
for (let i = 0; i < array.length; i++) {
  if (array[i] === stopValue) break;
  if (!uniqueArray.includes(array[i])) uniqueArray.push(array[i]);
}
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]

9. 异步场景下的数据去重

在前端开发中,异步操作是家常便饭。当处理异步获取的数据时,我们同样需要确保数据的唯一性。这时,Promise和async/await就派上了用场。

const fetchData = async () => {
  const urls = ['url1', 'url2', 'url2', 'url3']; // 假设这些URL返回不同的数据
  const uniqueUrls = [...new Set(urls)];
  const fetchPromises = uniqueUrls.map(url => fetch(url).then(response => response.json()));
  const results = await Promise.all(fetchPromises);
  console.log(results); // 输出每个URL的响应数据
};
fetchData();

10. 更复杂的去重逻辑:自定义比较函数

在某些情况下,我们可能需要根据更复杂的逻辑来判断元素的唯一性。这时,我们可以编写自定义的比较函数来实现去重。

const array = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 2, name: 'Bob' }, // 重复元素
  { id: 3, name: 'Charlie' }
];

const uniqueArray = array.filter((item, index, self) => {
  return self.findIndex(el => el.id === item.id) === index;
});

console.log(uniqueArray); // 输出根据id去重后的数组

通过以上10种JavaScript前端数据去重方式的详细讲解和代码案例,相信你已经掌握了多种数据去重的技巧。在实际项目中,你可以根据具体需求和性能要求选择合适的方法。希望这篇文章能够对你的前端开发之旅提供有益的帮助。如果你有任何疑问或想要分享你的经验,欢迎在评论区留言交流!

看到这里的小伙伴,欢迎点赞、评论,收藏!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值