Created
March 27, 2018 08:23
-
-
Save Carduelis/862dda5ad52fab7b419f64cbe7f2a41c to your computer and use it in GitHub Desktop.
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
function flatten(array) { | |
const flattered = []; | |
array.forEach(item => { | |
if (Array.isArray(item)) { | |
flattered.push(...flatten(item)); | |
} else { | |
flattered.push(item); | |
} | |
}) | |
return flattered; | |
} | |
function flatten2(array) { | |
return array.reduce((acc, item) => { | |
Array.isArray(item) ? acc.push(...flatten(item)) : acc.push(item); | |
return acc; | |
}, []); | |
} | |
const testArray = [[[1,2,[3,5,[554,5,[1, []],6]]],4]]; | |
console.log('forEach', flatten(testArray)); | |
console.log('reduce', flatten2(testArray)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment