Created
January 17, 2017 06:11
-
-
Save ccerrato147/6ed8340a1d9db731c8301ea377497ed0 to your computer and use it in GitHub Desktop.
Flat an Array
This file contains hidden or 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
// 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