Created
September 6, 2017 18:58
-
-
Save ilio/83eab1d519176784f1aeb494e1b90490 to your computer and use it in GitHub Desktop.
javascript es6 shallow array flatten for 2,3...n levels
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
const deep2array = [ | |
['abc1', 'bcd1', 'def1'], | |
['abc2', 'bcd2', 'def2'], | |
['abc3', 'bcd3', 'def3'] | |
]; | |
const shallowFlatten = (p, c) => [...p, ...c]; | |
console.log(deep2array.reduce(shallowFlatten, [])) | |
/* output: | |
["abc1", "bcd1", "def1", "abc2", "bcd2", "def2", "abc3", "bcd3", "def3"] | |
*/ | |
const deep3array = [ | |
[ | |
['abc11', 'bcd11', 'def11'], | |
['abc12', 'bcd12', 'def12'], | |
], | |
[ | |
['abc21', 'bcd21', 'def21'], | |
['abc22', 'bcd22', 'def22'], | |
], | |
[ | |
['abc31', 'bcd31', 'def31'], | |
['abc32', 'bcd32', 'def32'], | |
] | |
]; | |
console.log(deep3array.reduce(shallowFlatten, []).reduce(shallowFlatten, [])) | |
/* output: | |
["abc11", "bcd11", "def11", "abc12", "bcd12", "def12", "abc21", "bcd21", "def21", "abc22", "bcd22", "def22", "abc31", "bcd31", "def31", "abc32", "bcd32", "def32"] | |
*/ | |
// inline | |
console.log(deep2array.reduce((p, c) => [...p, ...c], [])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment