Skip to content

Instantly share code, notes, and snippets.

@rastalamm
Last active December 7, 2016 23:28
Show Gist options
  • Save rastalamm/8752db31467aea6255bb8dd2fa42b790 to your computer and use it in GitHub Desktop.
Save rastalamm/8752db31467aea6255bb8dd2fa42b790 to your computer and use it in GitHub Desktop.
Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
'use strict'
const makeMeFlat = (arr) => {
let output = []; //define what we want to eventually return
if (arr && Array.isArray(arr)) { //make sure there is an input and it's an array
for(var i = 0; i < arr.length; i++) { //Loop through input
if (Array.isArray(arr[i])) { //The parameter is an array, we need to look into this; recursively
output = output.concat(makeMeFlat(arr[i])); //Redefine `output` as itself with the array concactenated to it, while recursively looping through the parameter
} else {
output.push(arr[i]); //The parameter is not an array, send it to the output
}
}
}
return output;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment