Skip to content

Instantly share code, notes, and snippets.

@ninjascribble
Last active September 23, 2018 15:32
Show Gist options
  • Save ninjascribble/4719939 to your computer and use it in GitHub Desktop.
Save ninjascribble/4719939 to your computer and use it in GitHub Desktop.
Quick 'n dirty JavaScript interview question #1
/**
* 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