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
Transactional Characteristics 1. Atomicity: After...
Contents of this article: Page hollow mask layer,...
Preface This article mainly introduces the releva...
The Kubernetes team recently announced that it wi...
Copy code The code is as follows: <html> &l...
Some of you may have heard that the order of trav...
Table of contents Introduction to Anaconda 1. Dow...
This article mainly introduces the typing effect ...
1. The first method is to use the unhup command d...
Table of contents 1. Subquery definition 2. Subqu...
After spending half the night on it, I finally ma...
Overview The builder pattern is a relatively simp...
Say it in advance Nodejs reads the database as an...
Vue2+elementui's hover prompts are divided in...
Websites without https support will gradually be ...