当前位置:网站首页>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]
边栏推荐
- Advanced level of C language (high level) pointer
- Fast quantitative, abbkine protein quantitative kit BCA method is coming!
- "Xiaodeng in operation and maintenance" meets the compliance requirements of gdpr
- L'étape avancée du pointeur de langage C (haut de gamme) pour l'enroulement des cocons
- Initial experience of teambiion network disk (Alibaba cloud network disk)
- 微博发布案例
- Deep learning Flower Book + machine learning watermelon book electronic version I found
- Leetcode-206. Reverse Linked List
- URP - shaders and materials - simple lit
- C language (high-level) data storage + Practice
猜你喜欢

$refs: get the element object or sub component instance in the component:

Leetcode-543. Diameter of Binary Tree

Sqlmap tutorial (IV) practical skills three: bypass the firewall

Flexible layout (II)

How to reduce inventory with high concurrency on the Internet

3、 High quality programming and performance tuning practical youth training camp notes

Leetcode-206. Reverse Linked List

计算机服务中缺失MySQL服务

科技云报道:从Robot到Cobot,人机共融正在开创一个时代

1141_ SiCp learning notes_ Functions abstracted as black boxes
随机推荐
About some details of final, I have something to say - learn about final CSDN creation clock out from the memory model
2022-07-06:以下go语言代码是否会panic?A:会;B:不会。 package main import “C“ func main() { var ch chan struct
計算機服務中缺失MySQL服務
Jenkins远程构建项目超时的问题
nacos
Tencent's one-day life
按键精灵脚本学习-关于天猫抢红包
Abnova immunohistochemical service solution
ASEMI整流桥RS210参数,RS210规格,RS210封装
IO流 file
mips uclibc 交叉编译ffmpeg,支持 G711A 编解码
1090: integer power (multi instance test)
Causes and solutions of oom (memory overflow)
Advanced practice of C language (high level) pointer
Interviewer: what development models do you know?
身边35岁程序员如何建立起技术护城河?
$refs: get the element object or sub component instance in the component:
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
resource 创建包方式
Mobx knowledge point collection case (quick start)