当前位置:网站首页>使用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 ]
边栏推荐
猜你喜欢
Data recovery software EasyRecovery supports recovery of all types of files
PostMan import certificate add certificate
[Cellular Automata] Simulation of emergency evacuation of disaster personnel under social force factors based on cellular automata with matlab code attached
Grid布局介绍
typescript89-展示任务列表功能
Qt中QFile、QByteArray QDataStream和QTextStream区别
谷歌翻译下载-免费谷歌翻译软件下载
Loadrunner结合Fiddler实现脚本的录制
LeetCode每日两题01:二分查找 (均1200道)
makefile文件编译
随机推荐
SEMRush如何寻找关键词用于投放广告
When the centralized platform is gone, everything derived from this platform will be in vain
Latex example reference
HCIP-R&S By Wakin自用笔记(3)OSPF之各类LSA及LSA更新规则
力扣刷题记录7.1-----707. 设计链表
Latex示例参考
【元胞自动机】基于元胞自动机模拟社会力因素下的灾害人员疏散应急仿真附matlab代码
String compression
VS中如何添加依赖的库
docker搭建redis主从复制,容器无法启动?
程序员的日常生活 | 每日趣闻
eladmin容器部署超详细过程
JDBC technology (2) - set up common sql and configuration files
Phenomenon 1 during RF debugging
The 7 taboos of time management summarized by the postgraduate students, how many have you won?
LeetCode每日两题01:有序数组的平方 (均1200道)方法:双指针
如何在群晖系统中安装cpolar(群晖6.X版)
线段树知识整理
入门数据库Days5
Go-8-Gin框架