Last active
August 29, 2015 14:20
-
-
Save crcarrick/3dfaf1162fff17d119c5 to your computer and use it in GitHub Desktop.
Function to flatten any array, no matter how many dimensions it has. I came up with it messing around after I got stumped on a test question re: flattening multi-dimensional arrays.
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
function flatten (arr) { | |
// create a property on the function object that acts as a | |
// 'static'-ish variable array to hold the output | |
// and another for the length of the original array (you'll see why later) | |
// this is pretty clever and not my idea but | |
flatten.output = flatten.output || []; | |
flatten.origLength = flatten.origLength || arr.length; | |
// loop over array | |
for (var i = 0; i < arr.length; i++) { | |
// if arr[i] is itself an array | |
if (arr[i] instanceof Array) { | |
// call flatten passing in arr[i] in order to go down into the nested array and flatten that | |
// this will keep happening until the function gets to the 'bottom' of that 'nest' | |
flatten(arr[i]); | |
// otherwise | |
} else { | |
// push arr[i] onto flatten.output array | |
flatten.output.push(arr[i]); | |
} | |
} | |
// store the output property in a new variable since I'm going to be deleting it in a second | |
var output = flatten.output | |
// if i === length of the original array, | |
// that means I'm at the end of the WHOLE multi-dimensional array | |
// and not just the end of one of the nested arrays | |
if (i === flatten.origLength) { | |
// delete the properties so the function is re-usable | |
// if I don't do this, the next time the function is called these properties still exist | |
// and that obviously screws everything up | |
delete flatten.origLength; | |
delete flatten.output; | |
} | |
// return output array | |
return output; | |
} | |
var test = [1,2,3,[4,5,[6,7,[8,[9,10]]]],'one','two',['dog',5,['cat','bird']],[{key: 'value'},[{key: 'value', key2: 'value2', foo: function () {return 'bar';}, nest: {nest: 'nested'}, nestArr: ['whoa','man']}]]]; | |
flatten(test); | |
/* | |
[ 1, | |
2, | |
3, | |
4, | |
5, | |
6, | |
7, | |
8, | |
9, | |
10, | |
'one', | |
'two', | |
'dog', | |
5, | |
'cat', | |
'bird', | |
{ key: 'value' }, | |
{ key: 'value', | |
key2: 'value2', | |
foo: [Function], | |
nest: { nest: 'nested' }, | |
nestArr: [ 'whoa', 'man' ] } ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment