Created
December 26, 2019 01:24
-
-
Save cjkihl/e8d27c7c72991a5801238d376a5c0573 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* For full implementation with tests etc, see https://github.com/caki0915/arrayFlatten | |
* | |
* @param {Array} array The array to flatten. | |
* @param {number} depth The recursion depth. | |
* @param {Array} result Used for recursion. | |
* @returns {Array} Returns the new flattened array. | |
*/ | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
const arrayFlatten = (array: Array<any> = null, depth = 10, result: Array<any> = []): Array<any> => { | |
if (array == null) { | |
return result; | |
} | |
for (const value of array) { | |
if (depth > 0 && Array.isArray(value)) { | |
if (depth > 1) { | |
arrayFlatten(value, depth - 1, result); | |
} else { | |
result.push(...value); | |
} | |
} else { | |
result[result.length] = value; | |
} | |
} | |
return result; | |
}; | |
export default arrayFlatten; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For full implementation with tests etc, see https://github.com/caki0915/arrayFlatten