How to use reduce to implement the flat method of arrays in JavaScript
This article mainly introduces JavaScript how to use reduce to achieve the array of flat method, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
Using reduce to implement the flat method of array
Because selfFlat depends on this pointing, you need to specify the this point of selfFlat when traversing the selfFlat, otherwise it will point to window by default and an error will occur.
The principle traverses the array through reduce. When an element of the array is still an array, it is reduced by the extended operator of ES6 (ES5 can use the concat method), and the array element may be nested internally, so you need to call selfFlat recursively.
At the same time, the native flat method supports a depth parameter to indicate the depth of dimensionality reduction, which defaults to 1, which reduces the dimension of the array by one level.
Passing in Inifity turns the incoming array into an one-dimensional array
The principle is to subtract the depth parameter by 1 per recursion. If the depth parameter is 0, the original array is returned directly.
Thank you for reading this article carefully. I hope the article "JavaScript how to use reduce to achieve the flat method of arrays" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!