技术文摘
常见的数组去重若干方法
2024-12-31 05:26:25 小编
常见的数组去重若干方法
在 JavaScript 编程中,数组去重是一个常见的需求。以下将介绍几种常见的数组去重方法。
方法一:使用 Set 数据结构
Set 是 ES6 新增的数据结构,它的一个重要特性就是成员的值都是唯一的。我们可以利用这一特性来实现数组去重。
let arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
let uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr);
方法二:使用 filter 方法
filter 方法创建一个新数组,其包含通过提供函数实现的测试的所有元素。
let arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
let uniqueArr = arr.filter((item, index, self) => self.indexOf(item) === index);
console.log(uniqueArr);
方法三:使用 reduce 方法
reduce 方法对数组中的每个元素执行一个提供的 reducer 函数(升序执行),将其结果汇总为单个返回值。
let arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
let uniqueArr = arr.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueArr);
方法四:先排序再去重
先对数组进行排序,然后依次比较相邻的元素,如果相同则跳过。
let arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
arr.sort((a, b) => a - b);
let uniqueArr = [arr[0]];
for (let i = 1; i < arr.length; i++) {
if (arr[i]!== arr[i - 1]) {
uniqueArr.push(arr[i]);
}
}
console.log(uniqueArr);
在实际应用中,选择哪种数组去重方法取决于具体的场景和需求。例如,如果对性能要求较高,可以优先考虑使用 Set 方法;如果需要在去重的过程中进行一些复杂的逻辑处理,可以选择 reduce 方法。
掌握这些常见的数组去重方法,能够让我们在编程中更加高效地处理数据,提升代码的质量和可读性。
- Pandas 怎样利用 np.array 函数或 tolist 方法去除数据中的 index
- Python pandas 遍历行数据的两种方法总结
- Python 借助 pandas 实现数据的特定排序
- 解决 pandas.str.replace 失效问题的办法
- Python 中继承冲突与继承顺序的全面解析
- Python 实现自动连接 SSH 的步骤
- Python 条件判断中 not、is、is not、is not None、is None 的代码示例
- 利用 OpenCV 实现拍摄图片的文字识别方法
- Python 类多继承的搜索次序
- Python Anaconda 与 Pip 配置清华镜像的源代码实例
- Python 输入的多种情形深度剖析(单行、多行与数组)
- Python 利用装饰器实现重试机制的深度解析
- Python 中利用 Matplotlib 绘图无法显示中文字体的两种解决办法
- Python 处理序列重叠难题
- Python 编程中 aiohttp 模块在异步爬虫里的基本用法