Skip to content

Instantly share code, notes, and snippets.

@ilio
Created September 6, 2017 18:58
Show Gist options
  • Save ilio/83eab1d519176784f1aeb494e1b90490 to your computer and use it in GitHub Desktop.
Save ilio/83eab1d519176784f1aeb494e1b90490 to your computer and use it in GitHub Desktop.
javascript es6 shallow array flatten for 2,3...n levels
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