Skip to content

Instantly share code, notes, and snippets.

@tvvignesh
Created October 15, 2016 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvvignesh/f0e8c813ff0312e562fbb4560ead19eb to your computer and use it in GitHub Desktop.
Save tvvignesh/f0e8c813ff0312e562fbb4560ead19eb to your computer and use it in GitHub Desktop.
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