Last active
September 23, 2018 15:32
-
-
Save ninjascribble/4719939 to your computer and use it in GitHub Desktop.
Quick 'n dirty JavaScript interview question #1
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
/** | |
* Given an array of n length, where each item in the array may be a letter, | |
* number or another array, write a function that will return a flattened | |
* array containing all the values in the original array and its children. | |
* | |
* Ex. | |
* | |
* var arr = [ 1, 'b', [ 'c', [ 4 ], 5], 'f']; | |
* flatten(arr) === [1, 'b', 'c', 4, 5, 'f']; | |
*/ | |
var arr = [ 1, 'b', [ 'c', [ 4 ], 5], 'f']; | |
function flatten(arr) { | |
var result = [] | |
, i = 0 | |
, len = arr.length; | |
for (i; i < len; i++) { | |
// Using instanceof because typeof will always return 'object', 'string', 'number' or 'undefined' | |
if (arr[i] instanceof Array) { | |
// Using recursion to account for n-dimensions | |
result = result.concat(flatten(arr[i])); | |
} | |
else { | |
result.push(arr[i]); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment