当前位置:网站首页>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]
边栏推荐
- 【leetcode】1020. Number of enclaves
- 抽丝剥茧C语言(高阶)指针进阶练习
- After 95, Alibaba P7 published the payroll: it's really fragrant to make up this
- 3、 High quality programming and performance tuning practical youth training camp notes
- 点亮显示屏的几个重要步骤
- Leetcode sword finger offer brush questions - day 20
- 电商常规问题part1
- Bi she - college student part-time platform system based on SSM
- 2022-07-06:以下go语言代码是否会panic?A:会;B:不会。 package main import “C“ func main() { var ch chan struct
- Talk about seven ways to realize asynchronous programming
猜你喜欢

Redis data migration

Interviewer: what development models do you know?

URP - shaders and materials - simple lit

ROS2规划系统plansys2简单的例子

計算機服務中缺失MySQL服務

About binary cannot express decimals accurately

4、 High performance go language release optimization and landing practice youth training camp notes

抽丝剥茧C语言(高阶)指针进阶练习

My ideal software tester development status

Sqlmap tutorial (IV) practical skills three: bypass the firewall
随机推荐
抽絲剝繭C語言(高階)指針的進階
机器人技术创新与实践旧版本大纲
JS small exercise
1090: integer power (multi instance test)
../ And/
Role of virtual machine
MySQL service is missing from computer service
Model application of time series analysis - stock price prediction
gatk4中的interval是什么??
C language (high-level) data storage + Practice
gslx680触摸屏驱动源码码分析(gslX680.c)
Interviewer: what development models do you know?
抽丝剥茧C语言(高阶)数据的储存+练习
PostgreSQL source code (59) analysis of transaction ID allocation and overflow judgment methods
三、高质量编程与性能调优实战 青训营笔记
@component(““)
Deep learning Flower Book + machine learning watermelon book electronic version I found
【leetcode】1020. Number of enclaves
$refs: get the element object or sub component instance in the component:
2022-07-06:以下go语言代码是否会panic?A:会;B:不会。 package main import “C“ func main() { var ch chan struct