Last active
August 29, 2015 14:22
-
-
Save azangru/93f16fc40ebde77cdd68 to your computer and use it in GitHub Desktop.
Flatten for underbar — recursive
This file contains hidden or 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
// By the way — no idea why the function definition contains 'result' as a second argument; | |
// this is not present in the Underscore library. | |
_.flatten = function(nestedArray, result) { | |
var resultingArray = []; | |
_.each(nestedArray, function(element, index, nestedArray){ | |
flattenHelper(element, resultingArray); | |
}); | |
return resultingArray; | |
}; | |
function flattenHelper(element, array){ | |
if (Array.isArray(element) === false){ | |
array.push(element); | |
} else { | |
_.each(element, function(item, i, element){ | |
flattenHelper(item, array); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment