当前位置:网站首页>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 ]
边栏推荐
- 最新豆瓣top250爬虫案例代码分析[注释齐全]
- JDBC技术(二)——设置通用的sql和配置文件
- Image denoising based on edge enhancement Diffusion 】 (cEED) and Coherence Enhancing coursing together (cCED) filter to realize image denoising matlab code
- ffplay playback control
- UsernameAuthenticationFilter授权成功后调用AuthenticationSuccessHandler时的解析
- 配置文件的读取-TOML
- 力扣刷题记录1.5-----367. 有效的完全平方数
- 力扣刷题记录--常用功能函数
- 谷歌翻译软件-免费谷歌翻译
- PMP有什么答题技巧?
猜你喜欢

seaborn 笔记: 绘制分类数据
![[Cellular Automata] Simulation of emergency evacuation of disaster personnel under social force factors based on cellular automata with matlab code attached](/img/c3/77fba03e3615485fbbed43d1bc22be.png)
[Cellular Automata] Simulation of emergency evacuation of disaster personnel under social force factors based on cellular automata with matlab code attached

虹科技术|如何阻止供应链攻击?

Bugs encountered in remote control projects

Proe/Creo智能硬件产品结构设计要点「干货分享」

如何在EasyDSS中使用ffmpeg实现点播视频的拼接与合成?

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

Introduction to LVGL (based on v8.1-8.2)

《LC刷题总结》——贪心

字节输入流(InputStream)与字节输出流(OutputStream)
随机推荐
Go-10-模块与包
torchversion.transforms的使用
Latex example reference
Z-Game on grid(牛客多校赛)
方法参数
gstreamer 记录
MAYA发动机建模
Go-12-结构体
任务六 特征衍生 案例分析
Qt中QFile、QByteArray QDataStream和QTextStream区别
LeetCode每日两题01:二分查找 (均1200道)
RF调试过程中现象一
The server quit without updating PID file (/usr/local/mysql/data/localhost.pid).
2022眼康品牌加盟展,北京视力保健展,中国眼科医学技术峰会
使用JS实现数组扁平化的几种方式
ONNX是什么?怎么用?[简明解读版]
力扣刷题记录--常用功能函数
webrtc 编译
eladmin容器部署超详细过程
Design of Go-7-RESTful API