Skip to content

Instantly share code, notes, and snippets.

@ahafidi
Created September 27, 2021 12:39
Show Gist options
  • Save ahafidi/8b50a8f6a081a533c8f908c7986ff0d8 to your computer and use it in GitHub Desktop.
Save ahafidi/8b50a8f6a081a533c8f908c7986ff0d8 to your computer and use it in GitHub Desktop.
const flattenDepth = (arr, depth = 1) =>
arr.reduce(
(acc, cv) => [
...acc,
...(depth === 0 || !Array.isArray(cv)
? [cv]
: flattenDepth(cv, depth - 1))
],
[]
);
// flattenDepth([1, [2, [3, [4]], 5]], 3) => [1, 2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment