当前位置:网站首页>Several ways to use JS to achieve array flattening
Several ways to use JS to achieve array flattening
2022-08-09 02:03:00 【MomentYY】
数组扁平化的方式
什么是数组扁平化?
数组扁平化:Refers to converting a multidimensional array into a one-dimensional array.
例:Flatten the following array.
const arr = [1, [2, 3, [4, 5]]] // ---> [ 1, 2, 3, 4, 5 ]
1.使用flat()
flat()方法是ES10提出的,It recursively traverses the array to a specified depth,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回.(flat意为“水平的;平坦的”)
const result1 = arr.flat(Infinity) // Specifies that the depth is infinite
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.使用正则
The array elements obtained by the following methods will be turned into strings,不建议使用;
const result1 = JSON.stringify(arr).replace(/\[|\]/g, '').split(',') console.log(result1) // [ '1', '2', '3', '4', '5' ] Array elements are all turned into stringsThe above methods are optimized;
const result2 = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']') console.log(result2) // [ 1, 2, 3, 4, 5 ]
3.使用reduce()+concat()
使用reduceGet the current value and the previous value of the array,Determines whether the current value is an array,初始值设置为
[],然后使用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.使用函数递归
循环遍历数组,Recursive processing is performed when an array element is found,Finally convert the array to a one-dimensional array.
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()
ES6The newly introduced spread operator can reduce the dimensionality of arrays(One dimension reduction at a time),Loop to determine whether there is an array,进行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 ]
边栏推荐
猜你喜欢

New Swagger3.0 tutorial, OAS3 quick configuration guide, to automate API interface documentation!

The server quit without updating PID file (/usr/local/mysql/data/localhost.pid).

全文翻译:EDPB 基于设计和默认的数据保护指南

任务五 处理连续型数据

LeetCode每日一题:搜索插入位置 (均1200道)方法:二分查找

JDBC技术(一)——一个简单的JDBC测试

在树莓派上使用cpolar(番外篇2)

力扣刷题记录9.1-----24. 两两交换链表中的节点

LeetCode每日两题02:第一个错误的版本 (均1200道)方法:二分查找

Grid布局介绍
随机推荐
力扣刷题记录1.5-----367. 有效的完全平方数
力扣刷题记录5.1-----59. 螺旋矩阵 II
MT4/MQL4入门到精通外汇EA教程第一课 认识MetaEditor
ICMP差错报告报文数据字段
软件开发之我的一点想法
Go-8-Gin framework
2022眼康品牌加盟展,北京视力保健展,中国眼科医学技术峰会
LeetCode每日两题01:有序数组的平方 (均1200道)方法:双指针
MT4/MQL4入门到精通EA课程第二课-常用的功能函数
全文翻译:EDPB 基于设计和默认的数据保护指南
Dapr学习(4)之eShopOnDapr部署(Rancher2.63&k3s)
全文翻译:EDPB数据保护影响评估(DPIA:Data Protection Impact Assessment)指南
[C language brush questions] Application of fast and slow pointers in linked lists
德语翻译-德语在线批量翻译软件
yii2的安装之路
SEMRush如何寻找关键词用于投放广告
MT4/MQL4入门到精通EA教程第一课-MQL语言常用函数(一)OrderSend()函数
OpenSceneGraph3.5.1编译
js实现数组去重的方式(7种)
配置文件的读取-TOML