当前位置:网站首页>Six methods of flattening arrays with JS
Six methods of flattening arrays with JS
2022-07-07 07:35:00 【Jiang_ JY】
Concept
Array flattening is to convert a multi-dimensional array into a one-dimensional array
[1,[2,[3,4,5]]] ==> [1,2,3,4,5]
Implementation method
The following is an introduction js To flatten the array 6 Ways of planting :
1、 Recursive implementation
Common recursive thinking is easy to understand , It's through loop recursion , Go through it one by one , If each item is still an array , So we're going down , Using the method of recursive program , To realize the connection of each item of the array .
let arr = [1, [2, [3, 4, 5]]];
function flatten(arr) {
let result = [];
for(let i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
console.log(flatten(arr)); // [1, 2, 3, 4,5]
2、reduce Function iteration
As you can see from the ordinary recursive function above , In fact, it is to process every item of the array , In fact, it can also be used reduce To realize the splicing of arrays , Thus simplifying the code of the first method , The modified code is as follows :
let arr = [1, [2, [3, 4]]];
function flatten(arr) {
return arr.reduce(function(prev, next){
return prev.concat(Array.isArray(next) ? flatten(next) : next)
}, [])
}
console.log(flatten(arr));// [1, 2, 3, 4,5]
3、split and toString
Can pass split and toString Two ways to flatten the array together , Because the array will default to one toString Methods , So you can convert the array directly to a comma separated string , And then use split Method to convert the string back to an array , This is shown in the following code :
let arr = [1, [2, [3, 4]]];
function flatten(arr) {
return arr.toString().split(',');
}
console.log(flatten(arr)); // [1, 2, 3, 4,5]
4、 Through the extension operator
Implementation of this method , The extension operator and some Methods , Use both together , To flatten the array :
let arr = [1, [2, [3, 4]]];
function flatten(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
console.log(flatten(arr)); // [1, 2, 3, 4,5]
5、ES6 Medium flat
We can also call ES6 Medium flat Method to flatten the array .flat The grammar of the method :arr.flat ( [depth] )
among depth yes flat Parameters of ,depth It can pass the expansion depth of the array ( It is not filled in by default 、 Values are 1), That is to expand an array . If the number of layers is uncertain , Parameters can be passed into Infinity, It means that no matter how many layers there are, they have to be spread out :
let arr = [1, [2, [3, 4]]];
function flatten(arr) {
return arr.flat(Infinity);
}
console.log(flatten(arr)); // [1, 2, 3, 4,5]
6、 Use regular and JSON Method
In the 4 It has been used in two methods toString Method , It's still using JSON.stringify First convert to a string , Then filter out the square brackets of the array in the string through the regular expression , Final reuse JSON.parse Convert it to an array :
let arr = [1, [2, [3, [4, 5]]], 6];
function flatten(arr) {
let str = JSON.stringify(arr);
str = str.replace(/(\[|\])/g, '');
str = '[' + str + ']';
return JSON.parse(str);
}
console.log(flatten(arr)); // [1, 2, 3, 4,5]
边栏推荐
- 1140_ SiCp learning notes_ Use Newton's method to solve the square root
- PostgreSQL source code (59) analysis of transaction ID allocation and overflow judgment methods
- Flutter riverpod is comprehensively and deeply analyzed. Why is it officially recommended?
- 95后CV工程师晒出工资单,狠补了这个,真香...
- Wechat applet full stack development practice Chapter 3 Introduction and use of APIs commonly used in wechat applet development -- 3.9 introduction to network interface (IX) extending the request3 met
- 基于Flask搭建个人网站
- Invalid table alias or column reference`xxx`
- JSON introduction and JS parsing JSON
- After 95, Alibaba P7 published the payroll: it's really fragrant to make up this
- ROS2规划系统plansys2简单的例子
猜你喜欢
关于二进制无法精确表示小数
After 95, the CV engineer posted the payroll and made up this. It's really fragrant
Flutter riverpod is comprehensively and deeply analyzed. Why is it officially recommended?
nacos
【Liunx】进程控制和父子进程
Summary of customer value model (RFM) technology for data analysis
Introduction to abnova's in vitro mRNA transcription workflow and capping method
[ANSYS] learning experience of APDL finite element analysis
Interviewer: what development models do you know?
95后CV工程师晒出工资单,狠补了这个,真香...
随机推荐
Jenkins远程构建项目超时的问题
resource 创建包方式
机器人技术创新与实践旧版本大纲
Bi she - college student part-time platform system based on SSM
Stockage et pratique des données en langage C (haut niveau)
直播平台源码,可折叠式菜单栏
Robot technology innovation and practice old version outline
95后CV工程师晒出工资单,狠补了这个,真香...
Rxjs - observable doesn't complete when an error occurs - rxjs - observable doesn't complete when an error occurs
Unity C function notes
What is the difference between TCP and UDP?
抽丝剥茧C语言(高阶)指针进阶练习
记一个并发规则验证实现
leetcode:105. 从前序与中序遍历序列构造二叉树
Dynamics CRM server deployment - restore database prompt: the database is in use
外包干了三年,废了...
gatk4中的interval是什么??
How to * * labelimg
Invalid table alias or column reference`xxx`
Model application of time series analysis - stock price prediction