Created
September 28, 2018 15:55
-
-
Save ty-cs/89c18a5c2a8004da10c0b8dab2e96f26 to your computer and use it in GitHub Desktop.
flatten.js
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 flatten = | |
(arr, depth = Infinity) => | |
arr.reduce( | |
(list, v) => | |
list.concat( | |
depth > 0 ? | |
(depth > 1 && Array.isArray(v) ? | |
flatten(v, depth - 1) : | |
v | |
) : | |
[v] | |
) | |
, []); | |
flatten([[0, 1], 2, 3, [4, [5, 6, 7], [8, [9, [10, [11, 12], 13]]]]], 0); | |
// [[0,1],2,3,[4,[5,6,7],[8,[9,[10,[11,12],13]]]]] | |
flatten([[0, 1], 2, 3, [4, [5, 6, 7], [8, [9, [10, [11, 12], 13]]]]], 1); | |
// [0,1,2,3,4,[5,6,7],[8,[9,[10,[11,12],13]]]] | |
flatten([[0, 1], 2, 3, [4, [5, 6, 7], [8, [9, [10, [11, 12], 13]]]]], 2); | |
// [0,1,2,3,4,5,6,7,8,[9,[10,[11,12],13]]] | |
flatten([[0, 1], 2, 3, [4, [5, 6, 7], [8, [9, [10, [11, 12], 13]]]]], 3); | |
// [0,1,2,3,4,5,6,7,8,9,[10,[11,12],13]] | |
flatten([[0, 1], 2, 3, [4, [5, 6, 7], [8, [9, [10, [11, 12], 13]]]]], 4); | |
// [0,1,2,3,4,5,6,7,8,9,10,[11,12],13] | |
flatten([[0, 1], 2, 3, [4, [5, 6, 7], [8, [9, [10, [11, 12], 13]]]]], 5); | |
// [0,1,2,3,4,5,6,7,8,9,10,11,12,13] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment