Last active
November 19, 2019 16:57
-
-
Save okovalov/afa30a7f94abfeb3095929dd237e4aba to your computer and use it in GitHub Desktop.
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
// An example of recursive flattering of a given data (potentially multidimensional) | |
// 1. | |
// concat all the arrays of a given array and return a new array with a result | |
const concat = arr => [].concat(...arr) | |
// recursively flattern a given data into a new array (ES6) | |
const flattern = el => Array.isArray(el) ? concat(el.map(flattern)) : Array.of(el) | |
// 2. | |
// An example of concat before ES6 | |
const concatPreES6 = arr => [].concat.apply([], arr) | |
// ES6 Flattern and concat in one line | |
const flatternOne = el => Array.isArray(el) ? [].concat(...el.map(flatternOne)) : Array.of(el) | |
const data = [ | |
[1], | |
[2, 3], | |
[4], | |
[ | |
[5, 6], | |
[ | |
{ baa: 'foo', zaaa: 123, sss: { roo: 'moo' } }, | |
[ | |
{ ba11: 'foo1', zaaa: 123, sss: { roo: 'moo' } }, | |
{ ba22: 'fo2', zaaa: 123, sss: { roo: 'moo' } } | |
], | |
[7], | |
[8, 9, {sol: '1', col: e => e + 2 }] | |
], | |
[ | |
[10], | |
[ | |
[11, { foo: 'bar', moo: [3,4,5, [6,7]]}], | |
[12, 13], | |
14 | |
], | |
15 | |
] | |
] | |
] | |
const result = flatternOne(data) | |
console.info(result) | |
/** | |
* Expected output | |
* | |
[ 1, | |
2, | |
3, | |
4, | |
5, | |
6, | |
{ baa: 'foo', zaaa: 123, sss: { roo: 'moo' } }, | |
{ ba11: 'foo1', zaaa: 123, sss: { roo: 'moo' } }, | |
{ ba22: 'fo2', zaaa: 123, sss: { roo: 'moo' } }, | |
7, | |
8, | |
9, | |
{ sol: '1', col: [Function: col] }, | |
10, | |
11, | |
{ foo: 'bar', moo: [ 3, 4, 5, [Array] ] }, | |
12, | |
13, | |
14, | |
15 ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment