Skip to content

Instantly share code, notes, and snippets.

@ty-cs
Created September 28, 2018 15:55
Show Gist options
  • Save ty-cs/89c18a5c2a8004da10c0b8dab2e96f26 to your computer and use it in GitHub Desktop.
Save ty-cs/89c18a5c2a8004da10c0b8dab2e96f26 to your computer and use it in GitHub Desktop.
flatten.js
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