Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flatten an array of nested arrays of integers
/**
* Flatten an Array of Arbitrarily nested Arrays of Integers
* into a Flat Array of Integers.
* @param {Array} intArray - Array of Numbers
* @param {Array} flatArray - Flatten array (recursive)
* @return {Array} - Array of Numbers
*
* Link to JSBin - http://jsbin.com/dofuneb/edit?js,output
*/
var flatten = function(intArray, flatArray) {
// Keep previous results if recursive
var results = flatArray || [];
if (intArray && intArray.length > 0) {
intArray.forEach(function(value) {
if (typeof value === 'number') {
results.push(value);
} else if (value instanceof Array) {
flatten(value, results);
}
});
}
// Flat array of numbers after evaluation
return results;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.