Created
December 3, 2018 10:52
-
-
Save kidsil/2888cfb37a5aff7b7e65667eba58fe4f to your computer and use it in GitHub Desktop.
Flatten Multidimensional Arrays
This file contains 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
'use strict'; | |
const arr = [1,[2],[[3]],[[[4]]]]; //example Array | |
//Solution one - classic | |
let flatArr = []; | |
const flatten = (elem) => { | |
if (Array.isArray(elem)) return elem.forEach(flatten); | |
return flatArr.push(elem); | |
}; | |
arr.forEach(flatten); | |
console.log('Solution one: '); | |
console.log(flatArr); | |
//Solution two - clever clogs | |
flatArr = arr.toString().split(',').map(el => parseInt(el)); | |
console.log('Solution two: '); | |
console.log(flatArr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment