Deep flatten and housekeeping
Changed original flatten to be named deepFlatten, added normal flatten, improved some other snippets.
This commit is contained in:
@ -1,10 +1,8 @@
|
||||
### Flatten array
|
||||
|
||||
Use recursion.
|
||||
Use `reduce()` to get all elements that are not arrays, flatten each element that is an array.
|
||||
Use `reduce()` to get all elements inside the array and `concat()` to flatten them.
|
||||
|
||||
```js
|
||||
const flatten = arr =>
|
||||
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? flatten(v) : v ), []);
|
||||
// flatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
||||
const flatten = arr => arr.reduce( (a, v) => a.concat(v), []);
|
||||
// flatten([1,[2],3,4) -> [1,2,3,4]
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user