1. Concept of array flatteningArray flattening is the process of converting a multidimensional array into a one-dimensional array. [1, [2, 3, [4, 5]]] ------> [1, 2, 3, 4, 5] 2. Implementation1. reduce Traverse each item in the array, if the value is an array, traverse recursively, otherwise function flatten(arr) { return arr.reduce((result, item)=> { return result.concat(Array.isArray(item) ? flatten(item) : item); }, []); }
// Find the sum of the values in the array: arr.reduce((total, item)=> { // total is the previous calculation result, item is the value of each item in the array return total + item; }, 0); 2. toString & split Call the function flatten(arr) { return arr.toString().split(',').map(function(item) { return Number(item); }) } Because each item in the array formed after split is a string, a map method is needed to traverse the array and convert each item into a numeric type. 3. join & split Like function flatten(arr) { return arr.join(',').split(',').map(function(item) { return parseInt(item); }) } 4. Recursion Recursively traverse each item, if it is an array, continue traversing, otherwise function flatten(arr) { var res = []; arr.map(item => { if(Array.isArray(item)) { res = res.concat(flatten(item)); } else { res.push(item); } }); return res; } 5. Spread Operator [].concat(...[1, 2, 3, [4, 5]]); // [1, 2, 3, 4, 5] Based on this result, we can do a traversal. If function flatten(arr) { while(arr.some(item=>Array.isArray(item))) { arr = [].concat(...arr); } return arr; } Summarize: This concludes this article about 5 You may also be interested in:
|
<<: Detailed explanation of the solution to docker-compose being too slow
Copy code The code is as follows: <!--[if !IE]...
The image can be easily pushed directly to the Do...
In order to save installation time, I used the of...
1. Docker startup problem: Problem Solved: You ne...
Table of contents 1. Introduction to label statem...
Problem Description In the login page of the proj...
In order to make the page display consistent betwe...
CSS image splicing technology 1. Image stitching ...
1. Introduction As we all know, in the applicatio...
1. Modify the Linux server docker configuration f...
When users install MySQL database for the first t...
1. Rendering 2. Source code HTML < body > &...
Mysql stored procedure 1. Create stored procedure...
Table of contents Preface 1. Check the file disk ...
This article uses an example to describe how MySQ...