Skip to content

Instantly share code, notes, and snippets.

@siddrc
Created October 3, 2017 07:14
Show Gist options
  • Save siddrc/cf2c2499f12a45f986dcad412ac65745 to your computer and use it in GitHub Desktop.
Save siddrc/cf2c2499f12a45f986dcad412ac65745 to your computer and use it in GitHub Desktop.
flattenArray
//[[1,2,[3]],4] -> [1,2,3,4]
var input = [
[[1,2,[3]],4]
];
//check if inputArrayItem is an array
//if yes process inputArrayItem again
//else put in outputArray
var output = [];
function processArray(inputArray) {
inputArray.forEach(function(inputArrayItem, inputArrayIndex) {
if (Array.isArray(inputArrayItem))
processArray(inputArrayItem)
else
output.push(inputArrayItem);
})
}
processArray(input);
//console.log("Input " + input);
//console.log("Output " + output)
//$> node flattenArray.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment