Rename js snippets
This commit is contained in:
29
snippets/js/s/flatten-array.md
Normal file
29
snippets/js/s/flatten-array.md
Normal file
@ -0,0 +1,29 @@
|
||||
---
|
||||
title: Flatten array
|
||||
type: snippet
|
||||
language: javascript
|
||||
tags: [array,recursion]
|
||||
cover: angry-waves
|
||||
dateModified: 2020-10-22T20:23:47+03:00
|
||||
---
|
||||
|
||||
Flattens an array up to the specified depth.
|
||||
|
||||
- Use recursion, decrementing `depth` by `1` for each level of depth.
|
||||
- Use `Array.prototype.reduce()` and `Array.prototype.concat()` to merge elements or arrays.
|
||||
- Base case, for `depth` equal to `1` stops recursion.
|
||||
- Omit the second argument, `depth`, to flatten only to a depth of `1` (single flatten).
|
||||
|
||||
```js
|
||||
const flatten = (arr, depth = 1) =>
|
||||
arr.reduce(
|
||||
(a, v) =>
|
||||
a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v),
|
||||
[]
|
||||
);
|
||||
```
|
||||
|
||||
```js
|
||||
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
|
||||
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
|
||||
```
|
||||
Reference in New Issue
Block a user