Skip to content

Instantly share code, notes, and snippets.

@cjkihl
Created December 26, 2019 01:24
Show Gist options
  • Save cjkihl/e8d27c7c72991a5801238d376a5c0573 to your computer and use it in GitHub Desktop.
Save cjkihl/e8d27c7c72991a5801238d376a5c0573 to your computer and use it in GitHub Desktop.
/**
* 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;
@cjkihl
Copy link
Author

cjkihl commented Dec 26, 2019

For full implementation with tests etc, see https://github.com/caki0915/arrayFlatten

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment