当前位置:网站首页>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]
边栏推荐
- Build personal website based on flask
- 1、 Go knowledge check and remedy + practical course notes youth training camp notes
- Example of Pushlet using handle of Pushlet
- [cloud native] how to give full play to memory advantage of memory database
- Torefs API and toref API
- 1141_ SiCp learning notes_ Functions abstracted as black boxes
- Why is the row of SQL_ The ranking returned by number is 1
- 按键精灵采集学习-矿药采集及跑图
- The annual salary of general test is 15W, and the annual salary of test and development is 30w+. What is the difference between the two?
- About some details of final, I have something to say - learn about final CSDN creation clock out from the memory model
猜你喜欢
Jenkins远程构建项目超时的问题
MobaXterm
[2022 CISCN]初赛 web题目复现
【Liunx】进程控制和父子进程
About binary cannot express decimals accurately
身边35岁程序员如何建立起技术护城河?
L'étape avancée du pointeur de langage C (haut de gamme) pour l'enroulement des cocons
科技云报道:从Robot到Cobot,人机共融正在开创一个时代
English translation is too difficult? I wrote two translation scripts with crawler in a rage
我理想的软件测试人员发展状态
随机推荐
Cloud backup project
Dynamics CRM server deployment - restore database prompt: the database is in use
Example of Pushlet using handle of Pushlet
$refs: get the element object or sub component instance in the component:
3、 High quality programming and performance tuning practical youth training camp notes
海思芯片(hi3516dv300)uboot镜像生成过程详解
PostgreSQL source code (60) transaction system summary
resource 创建包方式
Advanced practice of C language (high level) pointer
Jenkins远程构建项目超时的问题
Several important steps to light up the display
按键精灵采集学习-矿药采集及跑图
Initial experience of teambiion network disk (Alibaba cloud network disk)
UWB learning 1
URP - shaders and materials - simple lit
抽丝剥茧C语言(高阶)数据的储存+练习
Redis data migration
Tumor immunotherapy research prosci Lag3 antibody solution
Torefs API and toref API
BGP experiment (1)