Skip to content

Instantly share code, notes, and snippets.

@BilalAlGhazi
Created January 13, 2019 17:15
Show Gist options
  • Save BilalAlGhazi/dd9c7810e535f28491efd424168e580b to your computer and use it in GitHub Desktop.
Save BilalAlGhazi/dd9c7810e535f28491efd424168e580b to your computer and use it in GitHub Desktop.
/**
* Function to flatten an array of arbitrarily nested arrays of integers into a flat array of integers
*
* @param {Array} inputArray The array to be flattenned.
* @param {Array} resultArray The result array.
*/
flattenArray = (inputArray, resultArray) => {
inputArray.forEach(function(entry) {
if(entry.constructor === Array){
flattenArray(entry, resultArray);
} else {
resultArray.push(entry);
}
});
}
// Example usage
const a = [[1,2,[3]],4];
const rslt = [];
flattenArray(a, rslt);
console.log(rslt);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment