How JavaScript flattens n-dimensional arrays
Editor to share with you how JavaScript flattened n-dimensional array, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Flattened n-dimensional array
1. The ultimate piece
[1, [2recollection 3]] .flat (2) / / [1, [2pr 3, [4pje 5]] .flat (3) / / [1, [2pr 3, [4pr 5]] .toString () / / '1pint 2, [4pr 5]] .toString () / /' 1pint 2, [4pr 5 [...] .flat (Infinity) / [1pr 2, [..] .flat (n) / [1pr 2, [4jue 5] .flat (n) / [1pr 2, [4pr 5 [...] .flat (n) / [1, [2pr 3, [..] .flat (n)]
Array.flat (n) is the api,n representation dimension of the ES10 flat array. When n is Infinity, the dimension is infinite.
two。 The beginning
Function flatten (arr) {while (arr.some (item= > Array.isArray (item) {arr = [] .concat (.arr);} return arr;} flatten ([1, [2jue 3]) / / [1Med 2jue 3] flatten ([1, [2jue 3, [4jue 5]) / / [1m 2m 3e 4e 4e 5]
The essence is to use recursion and array merging method concat to achieve flattening.
These are all the contents of the article "how JavaScript flattens n-dimensional arrays". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!