Skip to content

Instantly share code, notes, and snippets.

@azangru
Last active August 29, 2015 14:22
Show Gist options
  • Save azangru/93f16fc40ebde77cdd68 to your computer and use it in GitHub Desktop.
Save azangru/93f16fc40ebde77cdd68 to your computer and use it in GitHub Desktop.
Flatten for underbar — recursive
// 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