Created
October 15, 2016 16:47
-
-
Save tvvignesh/f0e8c813ff0312e562fbb4560ead19eb to your computer and use it in GitHub Desktop.
Flatten an array of nested arrays of integers
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
/** | |
* 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