How to use JavaScript to achieve array flattening
This article is about how to use JavaScript to achieve array flattening. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
I. the concept of array flattening
Array flattening refers to changing a multi-dimensional array into an one-dimensional array.
[1, [2, 3, [4, 5]]-> [1, 2, 3, 4, 5] 2. Reduce
Traverses each item in the array, recursively traverses if the value is an array, otherwise concat.
Function flatten (arr) {return arr.reduce ((result, item) = > {return result.concat (Array.isArray (item)? Flatten (item): item;}, []);}
Reduce is a method of an array that receives a function as an accumulator, and each value in the array (from left to right) begins to shrink and is eventually evaluated to a value.
Reduce contains two parameters: the callback function, the initial value passed to total
/ / find the sum of the values of the array: arr.reduce ((total, item) = > {/ / total is the result of the previous calculation, and item is the value of the array return total + item;}, 0); 2. ToString & split
Call the toString method of the array, change the array into a string, and then use split to split it back to the array.
Function flatten (arr) {return arr.toString () .split (',') .map (function (item) {return Number (item);})}
Because each item in the split split array is a string, you need to use a map method to traverse the array to convert each item to a numeric value
3. Join & split
Like the toString above, join can also convert arrays to strings
Function flatten (arr) {return arr.join (',). Split (',') .map (function (item) {return parseInt (item);})} 4. Recursion
Recursively traverse each item, and continue traversing if it is an array, otherwise concat
Function flatten (arr) {var res = []; arr.map (item = > {if (Array.isArray (item)) {res = res.concat (flatten (item));} else {res.push (item);}}); return res;} 5. Extension operator
Es6's extension operator can turn a two-dimensional array into an one-dimensional array.
[] .concat (. [1, 2, 3, [4, 5]]); / [1, 2, 3, 4, 5]
Based on this result, we can do a traversal, and if the arr contains an array, use the extension operator once until there is none.
Function flatten (arr) {while (arr.some (item= > Array.isArray (item) {arr = [] .concat (.arr);} return arr;} Thank you for reading! On "how to use JavaScript to achieve array flattening" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!