Skip to content

Instantly share code, notes, and snippets.

@ccerrato147
Created January 17, 2017 06:11
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 ccerrato147/6ed8340a1d9db731c8301ea377497ed0 to your computer and use it in GitHub Desktop.
Save ccerrato147/6ed8340a1d9db731c8301ea377497ed0 to your computer and use it in GitHub Desktop.
Flat an Array
// The nested array
const nested = [[1,2,[3,[8,10]]],4];
// An array that will contain the flatten array
const flat = [];
// The function that runs through the array and flattens it
const scan = (el, arr) =>{
if(!Array.isArray(el))
throw "The first parameter should be an array";
if(!Array.isArray(arr))
throw "The second parameter should be an array";
// loops through the nested array
el.forEach(e => {
// If the current element is also an array then the scan method is called again
if(Array.isArray(e))
scan(e, arr);
else // if it's not an array it gets inserted into the flat array
arr.push(e);
});
}
// run the scan function described above
scan(nested, flat);
// print the flat array
console.log(flat);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment