Created
December 23, 2017 17:02
-
-
Save mahmed8003/8b44955500529a572c6fa79caf176664 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Converts nested arrays into one-dimensional flattening array (recursively) | |
* @param {Array} arr Input nested arrays | |
* @param {Array} result Output one-dimensional flattening array | |
* @return Output one-dimensional flattening array | |
*/ | |
function flattenNestedArrays(arr, result = []) { | |
const length = arr.length; | |
for (let i = 0; i < length; i++) { | |
const value = arr[i]; | |
if (Array.isArray(value)) { // if the current element is an Array then call flattenNestedArrays recursively to flattening this array | |
flattenNestedArrays(value, result); | |
} else { | |
result.push(value); // if it is normal element then just push into array | |
} | |
} | |
return result; | |
}; | |
// execution test | |
const inputArray = [[1, 2, [3]], 4]; | |
const result = flattenNestedArrays(inputArray); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment