Last active
June 22, 2017 21:06
-
-
Save proshoumma/640d5e900d9d4495fdfb6695270154e2 to your computer and use it in GitHub Desktop.
Flatten out an array
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
/** | |
* flatten out an array | |
* @param {Array} input | |
* @param {Array} [output=[]] | |
* @return {Array} | |
*/ | |
const flatten = (input, output = []) => { | |
// current index | |
let index = output.length; | |
// loop through array values | |
for (let i = 0; i < input.length; i++) { | |
const value = input[i]; | |
// check if current value is an array | |
if (Array.isArray(value)) { | |
// recursive call to flat out the array value | |
flatten(value, output); | |
} else { | |
// insert the value into output array | |
if (value) output[index++] = value; | |
} | |
} | |
return output; | |
} | |
// tests | |
console.log(flatten([1, 2, 3])); | |
// => [ 1, 2, 3 ] | |
console.log(flatten([1, 2, [[[3]]]])); | |
// => [ 1, 2, 3 ] | |
console.log(flatten([1, 2, [], [], [[[3]]]])); | |
// => [ 1, 2, 3 ] | |
console.log(flatten([1, [[2]], , [[], [4]], [[[3]]]])); | |
// => [ 1, 2, 4, 3 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment