当前位置:网站首页>使用JS实现数组扁平化的几种方式
使用JS实现数组扁平化的几种方式
2022-08-09 01:56:00 【MomentYY】
数组扁平化的方式
什么是数组扁平化?
数组扁平化:指将一个多维数组转化为一个一维数组。
例:将下面数组扁平化处理。
const arr = [1, [2, 3, [4, 5]]] // ---> [ 1, 2, 3, 4, 5 ]
1.使用flat()
flat()方法是ES10提出的,它会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。(flat意为“水平的;平坦的”)
const result1 = arr.flat(Infinity) // 指定深度为无限
console.log(result1) // [ 1, 2, 3, 4, 5 ]
const result2 = arr.flat(1) // 指定深度为1
console.log(result2) // [ 1, 2, 3, [ 4, 5 ] ]
const result3 = arr.flat(2) // 指定深度为2
console.log(result3) // [ 1, 2, 3, 4, 5 ]
2.使用正则
以下做法得到的数组元素都会变成字符串,不建议使用;
const result1 = JSON.stringify(arr).replace(/\[|\]/g, '').split(',') console.log(result1) // [ '1', '2', '3', '4', '5' ] 数组元素都变成了字符串对以上方法进行优化处理;
const result2 = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']') console.log(result2) // [ 1, 2, 3, 4, 5 ]
3.使用reduce()+concat()
使用reduce拿到数组的当前值和前一项值,判断当前值是否为数组,初始值设置为
[],然后使用concat进行数组合并。
reduce()方法:对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
concat()方法:用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
function flatten(arr) {
return arr.reduce((pre, current) => {
return pre.concat(Array.isArray(current) ? flatten(current) : current)
}, [])
}
const result = flatten(arr)
console.log(result) // [ 1, 2, 3, 4, 5 ]
4.使用函数递归
循环遍历数组,发现含有数组元素就进行递归处理,最终将数组转为一维数组。
const result = []
function exec(arr) {
arr.forEach(item => {
if (Array.isArray(item)) {
exec(item)
} else {
result.push(item)
}
})
}
exec(arr)
console.log(result) // [ 1, 2, 3, 4, 5 ]
5.使用扩展运算符+concat()
ES6新推出的扩展运算符能对数组进行降维处理(一次降一维),循环判断是否含有数组,进行concat合并。
- some()方法:测试数组中是不是至少有1个元素通过了被提供的函数测试(它返回的是一个Boolean类型的值)。
function flatten(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr)
}
return arr
}
const result = flatten(arr)
console.log(result) // [ 1, 2, 3, 4, 5 ]
边栏推荐
- [深入研究4G/5G/6G专题-55]: L3信令控制-4-软件功能与流程的切分-CU网元的信令
- 【HNUMSC】C语言第二讲
- The Best Open Source Web Application Firewall to Protect Your Web Applications
- Go-8-Gin框架
- HCIP-R&S By Wakin自用笔记(2)OSPF之OSPF回顾、虚连接
- class path resource [bean.xml] cannot be opened because it does not 错误解决方案
- pytorch相关知识点总结
- 力扣刷题记录6.1-----203. 移除链表元素
- PostMan import certificate add certificate
- LeetCode每日两题02:第一个错误的版本 (均1200道)方法:二分查找
猜你喜欢

谷歌翻译下载-免费谷歌翻译软件下载

ffplay playback control

ROS2 ERROR: OpenGL 1.5 is not supported in GLRenderSystem::initialiseContext at C:\ci\ws\build...

任务六 特征衍生 案例分析

mysql连接超过八小时报错

typescript90-使用类型文件声明类型
![[C language brush questions] Application of fast and slow pointers in linked lists](/img/de/907192f705d9b2dc1628d480c4d7d9.png)
[C language brush questions] Application of fast and slow pointers in linked lists

JDBC技术(二)——设置通用的sql和配置文件

Using ngrok on Raspberry Pi (Extra 2)

The Best Open Source Web Application Firewall to Protect Your Web Applications
随机推荐
椭圆曲线复习
LeetCode精选200道--双指针篇
New Swagger3.0 tutorial, OAS3 quick configuration guide, to automate API interface documentation!
全文翻译:欧盟第29条数据保护工作组 数据保护官指南
gstreamer 记录
TCP/IP协议栈
LeetCode每日两题01:二分查找 (均1200道)
Codeforces Round #809 (Div. 2)A~D1
HNUMSC-C语言第一课
等到中心化的平台不再,衍生于这个平台的一切都将化作泡影
The Best Open Source Web Application Firewall to Protect Your Web Applications
Oracle最后一个商用免费版本JDK1.8.202
KQL和Lucene的区别
.reduce()的简单例子
深度学习模型的两种部署:ONNX与Caffe
任务六 特征衍生 案例分析
LVGL简介(基于v8.1-8.2)
typescript89-展示任务列表功能
【Unity】判断鼠标是否点击在UI上
【物理应用】基于El-centro地震波作用下隔震与非隔震支座下的顶层位移、速度、加速度的对比情况附matlab代码